0

I'm trying to build this simple project but I keep getting the same error. Can anybody help figure this out?

HibernateTest.java

public class HibernateTest
{
    public static void main(String[] args) 
    {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        UserDetails user = new UserDetails();

        Query query = session.getNamedQuery("findById");

        List<?> list = query.list();
        if (!list.isEmpty())
        { UserDetails userD = (UserDetails) list.get(0);
          System.out.println(userD); }
     }
}

UserDetails.java

package com;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Entity
@Table (name="UserDetails")
@NamedQuery(
        name = "findById",
        query = "SELECT x FROM UserDetails x WHERE x.id = '3'")
public class UserDetails
{
    @Id
    @Column(name="UserID")
    private int id;
    @Column(name="UserName")
    private String name;

    public void setId(int id)
    { this.id = id; }
    public int getId()
    { return id; }

    public void setName(String name) 
    { this.name = name; }
    public String getName()
    { return name; }
}

I'm not exactly sure what's wrong because I have the same query running in a different project and it works fine.

Jurgen Malinao
  • 149
  • 1
  • 1
  • 5

3 Answers3

0

I got the same issue and i have resolved the issue by adding the following in applicationContext.xml.

<property name="annotatedClasses">  
              <list>
               <value>com.Employee</value>
               </list>  
               </property>
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

If you are using XML configuration, you can define a named query with the <query> tag. For example:

<query name = "findById">
    <![CDATA[SELECT x FROM UserDetails x WHERE x.id = '3']]>
</query>

The <query> tag is on the same level as the <class> tag, as a child of the <hibernate-mapping> tag.

Jack
  • 2,937
  • 5
  • 34
  • 44
0

While this will not answer your immediate problem, if you are using Hibernate, and JPA annotations, why not using EntityManager instead of Hibernate session and stuff ?

With a Persistence Unit (as well as persistence.xml in your META-INF folder), you would do that:

EntityManagerFactory emf = 
Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager em = emf.createEntityManager();
Query query = em.createNamedQuery("findById");

Or better:

TypedQuery<UserDetails> query = em.createNamedQuery("findById", UserDetails.class);

The method are roughly the same (after all, JPA was made of Hibernate).

NoDataFound
  • 11,381
  • 33
  • 59