简体   繁体   中英

How does composition work in Hibernate?

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 identifier specified for entity org.bla.Bar

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.

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.

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 theHibernate 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM