简体   繁体   English

如何使用@OneToOne将不同的实体作为属性添加到对象

[英]how to add different entity as a property to object with @OneToOne

I have two entities in my application: House and Photo . 我的应用程序中有两个实体: HousePhoto

House has a property mainPhoto which has a @OneToOne relation to Photo House有一个属性mainPhoto ,它与Photo具有@OneToOne关系

Everything works fine here. 这里一切都很好。 Now I want to create a form for an admin where he will be able to add a new House . 现在,我想为管理员创建一个表单,他可以在其中添加新的House I want to add an upload field where he can select a Photo . 我想添加一个上传字段,他可以在其中选择Photo

How can I get this Photo , put it in a table named photo (create an object from it with some predefined values + this photo) and set the relationship between them? 我如何获取这张Photo ,将其放在名为photo的表中(使用一些预定义值和这张照片从中创建对象)并设置它们之间的关系?

This should be rather trivial in JPA. 在JPA中,这应该是微不足道的。

After the upload, instantiate a Photo object and assign it to the mainPhoto property of House . 上传后,实例化一个Photo对象并将其分配给HousemainPhoto属性。 Then just merge the result into the persistent context. 然后只需将结果合并到持久性上下文中即可。 Make sure you have merge cascading enabled on the relation. 确保已在关系上启用合并级联。

Basically something along the lines of: 基本上是这样的:

Photo photo = new Photo();
// set photo properties according to uploaded file

house.setMainPhoto(photo);
entityManager.merge(house);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM