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?
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.
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.
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.
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.
Use addAnnotatedClass
instead of addClass
Configuration.addClass()
indeed expects a companion hbm.xml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With