我有一个Product类和一个类Part ,其中每个部件只能属于一个产品。 每个产品都有一个部件清单,但有一部分没有参考其产品。
@Entity @Table (name= "products") class Product { @Id @GeneratedValue @Column(name = "Id") int id; @Column(name = "Name") String name; @??? List<Part> myParts;部分:
@Entity @Table (name= "parts") class Part { @Id @GeneratedValue @Column(name = "Id") int id; @Column(name = "Name") String name; }在我的数据库中,表'products'不存储有关其部件的信息,但'parts'表跟踪'product_id'行中的产品。
产品:
| id | 名字|
部分:
| id | 名字| procuct_id |
我认为使用OO-和ORM“世界”这种相反的方法是很正常的,但是我不知道如何用Hibernate将我的对象持久化到这个结构中!
对于一对多注释,我只找到了part-id将存储在product表中的示例。 对于多对一,似乎我需要在我的零件对象中引用该产品,不是吗?
我希望我错了! ;)
有没有人知道是否有办法在不修改我的类或表结构的情况下映射它?
(如果你能用注释而不是用xml解释它,我会非常非常高兴:))
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 :) )
最满意答案
我认为你的意思是一对多的单向映射,尝试如下:
@OneToMany @JoinColumn(name="product_id") List<Part> myParts;你可以在这里看到一个例子, @OneToMany 。 查看该链接中的“示例3”。
注意:由于您在parts表中将product_id作为外键,因此建议在Part类中也有Product type字段。
I think you mean a one-to-many unidirectional mapping, try something as follows:
@OneToMany @JoinColumn(name="product_id") List<Part> myParts;You can see an example here, @OneToMany. Check out "Example 3" in that link.
Note: Since you have the product_id as foreign key in the parts table, it is advised to also have a Product type field in the Part class.
更多推荐
发布评论