Hi,
I have a sample program in hibernate. The program firsts populates a table called USER that I have created in MySql database. After that it runs a method called "retrieve()" which just a basic select query. The problem is the "create()" method in the code below runs well and creates 4 rows in DB but when the next method "retrieve()" runs, the line "queryResult.list()" in the code returns null. Should it not return all the 4 rows? Not only that, when I go back and check my database there is nothing in it which means that somehow "retrieve" method is also removing the data from the USER table. Here is my code:
****************************************************************************
package com.examscam.model;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class CrudRunner {
public static void main(
String args[]){
CrudRunner.create();
CrudRunner.retrieve();
}
//create records in database
public static void create(){
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(User.class);
SessionFactory factory = config.configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
User user = new User();
User user1 = new User();
User user2 = new User();
User user3 = new User();
user.setPassword("fun123");
user1.setPassword("fun456");
user2.setPassword("fun789");
user3.setPassword("fun11");
session.save(user);
session.save(user1);
session.save(user2);
session.save(user3);
session.getTransaction().commit();
}
//retrieve records from database
public static void retrieve(){
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(User.class);
SessionFactory factory = config.configure().buildSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
//create the query
Query queryResult = session.createQuery("from User");
System.out.println("queryResult:"+queryResult);
java.util.List allUsers;
allUsers = queryResult.list();
for(int i=0;i<allUsers.size();i++){
User nextUser = (User) allUsers.get(i);
System.out.println("nextUser "+i+nextUser.getPassword());
}
session.getTransaction().commit();
}
}
************************************************************************************
Also, I am using hibernate with annotations; here is how my User class looks like:
---------------------------
package com.examscam.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
@Entity
public class User {
private Long id;
private String password;
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static void main(String[] args){
//create the annotation configuration object
AnnotationConfiguration config = new AnnotationConfiguration();
//make hibernate aware of PJO
config.addAnnotatedClass(User.class);
//read and process hibernate.cfg.xml and JPA metadata
config.configure();
//create a table corresponding to POJO
//this is just a one time statement
/*new SchemaExport(config).create(true,true);*/
//create an instance of User object
User user = new User();
user.setPassword("hiberbegin");
//create a session factory
SessionFactory factory = config.buildSessionFactory();
//create a session object
Session session = factory.getCurrentSession();
//persist POJO
session.beginTransaction();
//session.saveOrUpdate(user);
session.save(user);
session.getTransaction().commit();
}
}
--------------------------
Here is how my 'hibernate.cfg.xml' file looks:
*****************************************************************
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.url">
jdbc:mysql://localhost/examscam</property>
<property name="connection.username">root</property>
<property name="connection.password">learnsql123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">
thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
*****************************************************************************************
Please note that in this XML file I have not mapped my User class since I am using Annotations. I think that we do not have to map POJO in this file while using annotations. Please let me know if my assumption is wrong.
I checked both session and query values, they are both not null and are as below:
Session value:
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]
Query:
QueryImpl(from User user)
It is the query.list() method that is returning null.
On a separate note, it is the code from Cameron McKenzie's book 'Hibernate made easy' (page 116).
Please help. I am totally stuck up