Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 699
ripper234 Avatar asked Dec 21 '22 20:12

ripper234


2 Answers

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.

like image 133
Sean Patrick Floyd Avatar answered Dec 24 '22 10:12

Sean Patrick Floyd


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.

like image 24
Ralph Avatar answered Dec 24 '22 09:12

Ralph