我们可以使用Hibernate EntityManager返回除了primarykey之外的任何其他属性的实体吗?

时间:2016-10-13 00:24:25

标签: hibernate orm

我想使用entityManager根据唯一代码获取对象。 那就是:

EntityManager em;

bizObj.setCustomer(em.getReference(Customer.class , customerId));  //This works

Can I do as follows: (Say customerCode is unique), I want to retrieve based on customercode


// Assume code is unique

entity.setCustomer(em.getReference(Customer.class , customerCode);  //This throws exception

异常;

Caused by: java.lang.IllegalArgumentException: Provided id of the wrong type for class xx.core.model.Business. Expected: class java.lang.Long, got class java.lang.String
    at org.hibernate.internal.SessionImpl.getReference(SessionImpl.java:3405)
    at org.jboss.as.jpa.container.AbstractEntityManager.getReference(AbstractEntityManager.java:502)

1 个答案:

答案 0 :(得分:0)

不使用getReference(),如果您阅读oracle文档,他们明确提到它应该是主键 https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html

如果您有唯一标识,则可以使用TypedQuery.getSingleResult()