我已经花了两天时间解决这个问题,而且我没有接近解决它。我希望其中一位专家可以提供帮助。
这就是问题所在。我使用TomEE 1.6.0.2(OpenEJB 4.6.0.2)并尝试执行一个返回单个结果的简单TypedQyery,并获得最奇怪的返回值。它不是我期望的bean对象 - 它是java.lang.Class !!
这是代码片段:
public static Account getAccount(String type, String key, EntityManager em) {
try {
TypedQuery<Account> query = em.createNamedQuery("Account.getByTypeAndKey", Account.class)
.setParameter("type", type)
.setParameter("key", key)
.setMaxResults(1);
Account account = query.getSingleResult(); // This statement throws an exception
}
catch (Exception e) {
System.out.println(e.getMessage()); // "java.lang.Class cannot be cast to beans.Account"
}
try {
TypedQuery<Account> query = em.createNamedQuery("Account.getByTypeAndKey", Account.class)
.setParameter("type", type)
.setParameter("key", key)
.setMaxResults(1);
Object object = query.getSingleResult(); // This works
System.out.printf("object is '%s'\n", object.toString());
// "object is 'class beans.Account'"
Account account = new Account();
System.out.printf("account is '%s'\n", account.toString());
// "account is 'Account{id=0, type='null, etc... }'"
return account;
}
catch (Exception e) {
System.out.println(e.getMessage()); // Never gets here
}
}
这是Account类的一个片段:
@Entity
@Table(name="Account")
@NamedQueries({
@NamedQuery(name = "Account.getByTypeAndKey", query = "SELECT Account FROM Account rec WHERE rec.key = :key AND rec.type = :type"),
})
public class Account implements Serializable {
private int id;
private String type;
// The usual stuff ...
}
这是persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="unipagosPersistenceUnit" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>PAY_AccountDSJta</jta-data-source>
<non-jta-data-source>PAY_AccountDSNonJta</non-jta-data-source>
<class>beans.Account</class>
<properties>
<property name="openjpa.DynamicEnhancementAgent" value="true"/>
<property name="openjpa.RuntimeUnenhancedClasses" value="supported"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=60000"/>
</properties>
</persistence-unit>
</persistence>
我确信这很容易,但我无法弄明白这一点。发生什么事了?!
TIA求助......
答案 0 :(得分:3)
您的查询错误。它应该是
SELECT rec FROM Account rec WHERE rec.key = :key AND rec.type = :type
^-- use the alias here, and not the class name