Retrieving records from Database in Hibernate

In my previous post I have used example for the insertion of data in Hibernate. Here is another example for selecting the records from the database using hibernate. In the same project (from previous post), I have added this new class named UsersList.java and ShowUser.java without making any other changed.

package ps.com;
//UsersList.java
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

import java.util.Iterator;
import java.util.List;

public class UsersList {
	public static void main(String[] args) {
		Session sess = null;
		try {
			SessionFactory sfact = new Configuration().configure().buildSessionFactory();
			sess = sfact.openSession();
			Criteria crit = sess.createCriteria(User.class);
			ProjectionList proList = Projections.projectionList();

			proList.add(Projections.property("u_name"));
			proList.add(Projections.property("u_password"));
			crit.setProjection(proList);
			List list = crit.list();
			Iterator it = list.iterator();
			if (!it.hasNext()) {
				System.out.println("Data does not exist");
			} else {
				System.out.println("User Name\t\tPassword");
				System.out.println("----------------------------------");
				while (it.hasNext()) {
					Object[] row = (Object[]) it.next();
					for (int i = 0; i < row.length; i++) {
						System.out.print(row[i] +"\t\t\t");

					}
					System.out.println();
				}
			}
			sess.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("Error :" + e.getMessage());
		}
	}
}

Output :

Most of the time we need to select single row with condition, which can be achieved from this piece of code.

package ps.com;
//ShowUser.java
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

public class ShowUser {
	public static void main(String[] args) {
		Session sess = null;
		try {
			SessionFactory sfact = new Configuration().configure()
					.buildSessionFactory();
			sess = sfact.openSession();

			User user = new User();
			user.setU_name("sharma");
			Example example = Example.create(user);
			Criteria crit = sess.createCriteria(User.class).add(example);

			ProjectionList proList = Projections.projectionList();
			proList.add(Projections.property("u_name"));
			proList.add(Projections.property("u_password"));
			crit.setProjection(proList);
			List list = crit.list();
			Iterator it = list.iterator();

			System.out.println("User Name\t\tPassword");
			System.out.println("----------------------------------");

			Object[] row = (Object[]) it.next();
			for (int i = 0; i < row.length; i++) {
				System.out.print(row[i] + "\t\t\t");

			}

			sess.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("Error :" + e.getMessage());
		}
	}
}

Output

Note: In this code, Example class that is used to add criteria is defined in imported package org.hibernate.criterion.

Adding Autoincrement Field using <generator/> in Hibernate

In  my previous post, We are adding id of the user by using parameter value to the constructor.  In general jsp, servlet code If id field is required to be auto increment, we will select the maximum value of the field and next value will be inserted into the field. Same operation is done by using  “incremental” class property of <generator> in Hibernate.

If we need to implement this funtionality to the previous example. We have to just remove id parameter from the constructor and edit the user id mapping to <generator/>. Changes has been highlighted in below piece of code.

 User.java

...
...
	public User(String u_name, String u_password)
	{
		this.u_name=u_name;
		this.u_password=u_password;
	}
...
...

User.hbm.xml

...
...
	<id name="u_id" type="integer" column="id">
		<generator class="increment"/>
	</id>
...
...		

Example.java

...
...
	session=sessionFactory.openSession();
	User user=new User("Sharma","newpassword");
	session.save(user);
....
...

My First Hibernate Example

As I began with Hibernate from yesterday, I went through this small example to insert a row into database table. I have done this example in MyEclipse workbench. In this example there are mainly four files to work with:

1)      hibernate.cfg.xml :

This xml file is used to configure the connection for the database. In MyEclipse, as we add the Hibernate capabilities to the project, this file will get created.

hibernate.cfg.xml will be configered like this:

<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
    	<property name="hibernate.connection.driver_class">
    		com.mysql.jdbc.Driver
    	</property>
		<property name="hibernate.connection.url">
			jdbc:mysql://localhost/test_db1
		</property>    
		<property name="hibernate.connection.username">
			root
		</property>
		<property name="hibernate.connection.password">
			root
		</property>
		<property name="hibernate.connection.pool_size">
			10
		</property>
		<property name="show_sql">
			true
		</property>
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="hibernate.hbm2ddl.auto">
			update
		</property>
		<mapping resource="User.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

2)      User.java

This is a persistence class which uses POJOs class to map the fields of the particular table. In next xml file we will have to map each of these variables with the fields of the table.

package ps.com;
//User.java
public class User {
	Integer u_id;
	String u_name;
	String u_password;
	public User()
	{

	}
	public User(Integer u_id,String u_name, String u_password)
	{
		this.u_id=u_id;
		this.u_name=u_name;
		this.u_password=u_password;
	}
	public Integer getU_id() {
		return u_id;
	}
	public void setU_id(Integer u_id) {
		this.u_id = u_id;
	}
	public String getU_name() {
		return u_name;
	}
	public void setU_name(String u_name) {
		this.u_name = u_name;
	}
	public String getU_password() {
		return u_password;
	}
	public void setU_password(String u_password) {
		this.u_password = u_password;
	}
}

3)      User.hbm.xml

In this xml file, we map the variable of the persistence class with the fields of the database table. In mysql, this file is created by right clicking on the project, new>xml(basic template)

Then provide the name of the xml file (User.hbm.xml), Click on next

Select “Create XML file from a DTD file” radio button, click on next

Select “Select XML category entry” radio button

Select “-//Hibernate/Hibernate Mapping DTD 3.0//EN” from the key list, click on next

Click on finish.

The properties will be mapped like this :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="ps.com.User" table="tbl_user">
		<id name="u_id" type="long" column="id">
			<generator class="assigned"/>
		</id>
		<property name="u_name">
			<column name="name"></column>
		</property>
		<property name="u_password">
			<column name="password"></column>
		</property>		
	</class>
</hibernate-mapping>

4)      Example.java

This is the file where we will write the code for reading the configuration file and database operations.

package ps.com;
//Example.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

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

			User user=new User(1,"Prashant","mypassword");
			session.save(user);
			session.beginTransaction().commit();
		}
		catch (Exception ex)
		{
			System.out.println("Error:" + ex);
		}
		finally
		{
			session.flush();
			session.close();
		}
	}
}

Before running the code, MySql.jar should be added to the project. And then you will need to add the Schema into the database.

As the output of this project, with the run of the Example.java, Table will be created according to the mapped setting and the given data in the example file will get saved.