gpt4 book ai didi

java - TypedQuery.getSingleResult 返回类型为 Class 而不是类型 T 的对象

转载 作者:行者123 更新时间:2023-11-29 05:22:50 25 4
gpt4 key购买 nike

我已经花了两天时间解决这个问题,但离解决它还差得很远。我希望其中一位专家可以提供帮助。

问题来了。我正在使用 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 为您提供帮助...

最佳答案

您的查询是错误的。应该是

SELECT rec FROM Account rec WHERE rec.key = :key AND rec.type = :type
^-- use the alias here, and not the class name

关于java - TypedQuery<T>.getSingleResult 返回类型为 Class 而不是类型 T 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23988075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com