[英]How to persist a property of type List<Object> in JPA?
What is the best way to get a List with Objects persisted? 持久保存对象列表的最佳方法是什么? I'm using JavaEE 7 with JPA. 我将JavaEE 7与JPA结合使用。 Object B is also an Entity. 对象B也是一个实体。
My Model 我的模特
@Entity
public class ObjectA implements Serializable {
@Id @GeneratedValue
private Long id;
// What should I use here?
private List<ObjectB> objectList;
public ObjectA () {
this.objectList = new ArrayList<ObjectB>();
}
}
My JPA Calls 我的JPA电话
@Stateless
@JPA
public class ObjectJPA{
@PersistenceContext(unitName = "ObjectProjectPU")
private EntityManager em;
// How can I insert a record in the table for objectList here?
public void insertIntoObjectList(ObjectB objectB) {
em.persist(objectB); // This must be wrong?
}
}
What I prefer is that my database table for objectList would look like this: 我更喜欢的是我的objectList数据库表如下所示:
id (ObjectA_id) | objectB_id or id | ObjectA_id | objectB_id
Your ObjectA class should look like below. 您的ObjectA类应如下所示。
@Entity public class ObjectA implements Serializable { @Id @GeneratedValue private Long id; // What should I use here? private List<ObjectB> objectList; @OneToMany(mappedBy = "objectB_id") public List<ObjectB> getObjectList() { return objectList; } public void setObjectList(List<ObjectB> listOfObjetB) { this.objectList = listOfObjetB; } public ObjectA () { this.objectList = new ArrayList<ObjectB>(); } }
This will create a relation between your class A and B. 这将在您的A类和B类之间建立关系。
Follow the example given to the below link properly. 正确遵循以下链接给出的示例。 It will help you to understand the JPA one to many relationship. 它将帮助您了解JPA一对多关系。 :) :)
I figured out that it was pretty easy. 我发现这很容易。
ObjectA Model ObjectA模型
@OneToMany
@JoinTable
(
name="OBJECTA_OBJECTB",
joinColumns={ @JoinColumn(name="ID", referencedColumnName="ID") },
inverseJoinColumns={ @JoinColumn(name="OBJECTB_ID", referencedColumnName="ID") }
)
private List<ObjectB> objectList;
JPA CALL JPA电话
public void insertIntoObjectList(ObjectB object) {
object.setSomeDataInObjectList(list); // just a random list here
em.persist(object);
}
ObjectB Model ObjectB模型
@ManyToOne
ObjectA objectA;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.