I have a class Product and a class Part, where every part can only belong to one one product. Each product has a list of its parts, but a part has no reference to its product.
@Entity
@Table (name= "products")
class Product {
@Id
@GeneratedValue
@Column(name = "Id")
int id;
@Column(name = "Name")
String name;
@???
List<Part> myParts;
parts:
@Entity
@Table (name= "parts")
class Part {
@Id
@GeneratedValue
@Column(name = "Id")
int id;
@Column(name = "Name")
String name;
}
In my database the table ‘products’ does not store information about its parts, but the ‘parts’ table keeps track of the products in a row ‘product_id’.
products:
| id | name |
parts:
| id | name | procuct_id |
I think it is quite normal to have this contrary approaches of the OO- and the ORM “world”, but I can’t find out how to persist my objects with Hibernate to this structure!
For the one-to-many annotation I only found examples where the part-id would have been stored in the product table.
For many-to-one it seems as if I needed a reference to the product in my parts objects, isn’t it?
I hope that I am wrong! 😉
Does anybody know if there is a way to map this without chaning my class or table structure?
( I would be very, very happy if you could explain it with annotations rather than with xml 🙂 )
I think you mean a one-to-many unidirectional mapping, try something as follows:
You can see an example here,
@OneToMany. Check out “Example 3” in that link.Note: Since you have the
product_idas foreign key in thepartstable, it is advised to also have aProducttype field in thePartclass.