I have spent literally two days on the problem and I'm no closer to solving it. I hope that one of the experts out there can help.
Here's the problem. I'm Using TomEE 1.6.0.2 (OpenEJB 4.6.0.2) and trying to do a simple TypedQyery that returns a single result and I am getting the strangest return value. It's not the bean object that I expect--it's a java.lang.Class!!
Here's the code fragment:
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
}
}
Here's a fragment of the Account class:
@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 ...
}
And here is 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>
I'm sure this is something really easy, but I'm not able figure this one out. What's going on?!
TIA for your help...
Your query is wrong. It should be
SELECT rec FROM Account rec WHERE rec.key = :key AND rec.type = :type
^-- use the alias here, and not the class name