2014-06-21 44 views
-1

我想问如何实现这样的事情像更新实体与@ManyToOne关系。我有两个表的文档和
@OneToMany(mappedBy = "doctype") private Collection<Documents> DocCollection;JPA MantyToOne更新实施

当用户需要更新的文档类型,他键入组合框至极值包含字符串的所有文档类型名称。后来我找到的文档类型实体的DocType类型一样,
Doucments
@JoinColumn(name = "doctype", referencedColumnName = "document_id") @ManyToOne private DocType doctype;
的DocType,其中doctype名称类似的值在组合框中选择,然后我将doctype实体设置为文档实体。
public void saveDoc() { entityManager.getTransaction().begin(); currentEntitydoc.setDocType(getDocTypeEntity(ComboBox.getSelectedValue())); entityManager.getTransaction().commit(); }

凡getDocTypeEntity()之类
public DocType getDocTypeEntity (String userInput) { query = manager.createQuery( "Select type from DocType type Where type.name=:arg1" ); query.setParameter("arg1" , userInput); List<DocType> list = query.getResultList(); if (list.size() < 1 ) { System.out.println ("can't find such DocType name); } return list.get(0); }

看来,这是一个很经常的任务,做u如何实现这样的事情? JPA中有更好的方法吗?

回答

0

实体具有唯一标识它们的标识。 EntityManager允许获得一个给定其类型和ID的实体。因此,所有你需要的是

DocType docType = em.find(DocType.class, docTypeId); 

甚至

DocType docType = em.getReference(DocType.class, docTypeId); 

它甚至不需要出具选择查询(并返回unitilized代理)。

您不应该使用Doctype的名称作为选择选项值,而是使用其ID。