How does composition work in Hibernate?

可紊 提交于 2019-12-24 03:47:09

问题


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


回答1:


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.




回答2:


You need to specifiy the realtionship between Foo and Bar (somthing like @ManyToOne or @OneToOne).

Or if Bar is not an own 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: http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-component-using-annotations-1.html -- The example expain the @Embeddable add @Embedded Composit way, where Foo and Bar (in the example: Student and Address) are mapped in the same Table.




回答3:


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
}


来源:https://stackoverflow.com/questions/4284836/how-does-composition-work-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!