2014-06-21 43 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。