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
The mechanism is described in this section of the reference docs:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With