开发者

How does composition work in Hibernate?

开发者 https://www.devze.com 2023-01-27 15:14 出处:网络
I\'m trying to use composition in hibernate with annotations. I have: @Entity @Table(name = \"Foo\") public class Foo {

I'm trying to use composition in hibernate with annotations.

I have:

@Entity
@Table(name = "Foo")
public class Foo {
    private Bar bar;

    public void setBar(Bar bar){...}
    public Bar getBar() {...)
}

public class Bar {
  private double x;

  public void setX(double x) {...}
  public double getX() {...}
}

And when trying to save Foo, I'm getting

Could not determine type for entity org.bla.Bar at table Foo for columns: [org.hibernate.mapping.Column(bar)]

I tried putting an @Entity annotation on Bar, but this gets me:

No i开发者_高级运维dentifier specified for entity org.bla.Bar


The mechanism is described in this section of the reference docs:

5.1.5. Embedded objects (aka components)

Apparently hibernate uses JPA annotations for this purpose, so the solution referred to by Ralph is correct

In a nutshell:

if you mark a class Address as @Embeddable and add a property of type Address to class User, marking the property as @Embedded, then the resulting database table User will have all fields specified by Address.

See Ralph's answer for the code.


You need to specifiy the relationship between Foo and Bar (with something like @ManyToOne or @OneToOne).

Alternatively, if Bar is not an Entity, then mark it with @Embeddable, and add @Embedded to the variable declaration in Foo.

@Entity
@Table(name = "Foo")
public class Foo {
    @Embedded
    private Bar bar;

    public void setBar(Bar bar){...}
    public Bar getBar() {...)
}

@Embeddable
public class Bar {
  private double x;

  public void setX(double x) {...}
  public double getX() {...}
}

See: https://www.baeldung.com/jpa-embedded-embeddable -- The example expains the @Embeddable and @Embedded Composite way, where Foo and Bar (Company and ContactPerson in the example) are mapped in the same Table.


Each simple entity must be marked as an entity (with @Entity) and have an identifier (mostly a Long) as a primary key. Each non-primitive association/composition must be declared with the corresponding association annotation (@OneToOne, @OneToMany, @ManyToMany). I suggest you read through the Hibernate Getting Started Guide. Try the following to make your code example work

@Entity
public class Foo {
    @Id
    @GeneratedValue
    private Long id;

    @OneToOne
    private Bar bar;

    // getters and setters for id and bar
}

@Entity
public class Bar {
    @Id
    @GeneratedValue
    private Long id;

    private double x;

    // getters and setters for id and x
}
0

精彩评论

暂无评论...
验证码 换一张
取 消