Translate

Tuesday, September 9, 2014

Hibernate NamedQueries and NamedNativeQueries Errors

Working on Android client/server project I ran into some problems with Hibernate 4.3.1 annotations and Java code for Named Queries and Native Named Queries. The errors I was receiving were along the lines of "error in named query". Below is an example of the annotations and code that finally worked for me when querying an MSSQL database. Note the differences between the NamedQuery and corresponding NativeNamedQuery.
For a MySQL database the NamedQuery did not work.

The annotations:

@Entity
@Table(name="Member")
@NamedQueries({
@NamedQuery(name="Member.loadByEmail", query="select m from Member m where email= :email"),
@NamedQuery(name="Member.loadByEmailAndPassword", query="select m from Member m where email= :email and password= :pwd")
})
@NamedNativeQueries({
@NamedNativeQuery(name="Member.nLoadByEmail", query="select m.* from Member m where email= :email", resultClass=Member.class),
@NamedNativeQuery(name="Member.nLoadByEmailAndPassword", query="select m.* from Member m where email= :email and password= :pwd", resultClass=Member.class)
})
public class Member implements Serializable{...

The code to create the query:

public Object findMemberByEmail(String email){
  return em.createNamedQuery("Member.LoadByEmail", Member.class).setParameter("email", email).getSingleResult();
}

public Object nFindMemberByEmail(String email){
  return em.createNamedQuery("Member.nLoadByEmail").setParameter("email", email).getSingleResult();
}

No comments:

Post a Comment

Thank you for commenting!