Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate MappingNotFoundException when using annotations to map an Entity class

Tags:

java

hibernate

I'm new to Hibernate. I'm trying to run a simple query to see if the given login information for a user is correct:

public boolean checkLogin(String user, String pw)
{    
    pw = Util.encrypt(pw);

    String sql = "select count(*) from User where email = :email and pw = :pw";
    Query q = HibernateUtil.getSession().createQuery(sql);

    q.setParameter("email", user);
    q.setParameter("pw", pw);

    int count  = ( (Integer)  q.iterate().next() ).intValue();

    return count > 0;
}

When I call this method, I get an exception which says User class is not mapped.

To fixed this, I created this user class:

import javax.persistence.*;

@Entity @Table(name = "user")
public class User
{
    @Id @GeneratedValue
    @Column(name = "id")
    private Long id;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }
}

And in my HibernateUtils.createSession I added the following line:

configuration.addClass(User.class);

However this gives me the exception:

Caused by: org.hibernate.MappingNotFoundException: resource: 
net/myProject/server/model/User.hbm.xml not found
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:741)
    at org.hibernate.cfg.Configuration.addClass(Configuration.java:786)
    at net.myProject.server.util.HibernateUtil.<clinit>(HibernateUtil.java:28)

What am I doing wrong?

like image 589
Ali Avatar asked Feb 08 '14 17:02

Ali


People also ask

How do you map a class in Hibernate?

Define Hibernate Mapping FileThe <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.

Is @entity annotation mandatory in Hibernate?

The entity class must be annotated with the Entity annotation or denoted in the XML descriptor as an entity. So, if you use annotations for mappings, @Entity is mandated by the specification and Hibernate has to adhere to it.

Which annotation is used to map a field in class onto a column in Table?

JPA annotations are used in mapping java objects to the database tables, columns etc. Hibernate is the most popular implement of JPA specification and provides some additional annotations.

How to resolve Hibernate Exception?

This exception occurs frequently while reattaching a detached object with a session by calling the update method. If the session has another instance with the same identifier loaded, then we get this error. In order to fix this, we can use the merge method to reattach the detached object.


1 Answers

Use addAnnotatedClass instead of addClass

Configuration.addClass() indeed expects a companion hbm.xml

like image 138
Ori Dar Avatar answered Oct 05 '22 12:10

Ori Dar