Home Hibernate Hibernate4.2 Hibernate Load Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Hibernate Load Example

Advertisement
The Hibernate Load Example uses the session.load() method to load the entity from database based on its primary key. This is very convenient method of loading the entity using its primary key.

Hibernate Load Example - Learn how to use the session.load() method for finding an entity by its primacy key

Example explained here teaches you how to use the session.load() method to load an entity by its primary key.

Here is the most used method for loading the entity:

load(Class theClass, Serializable id)

This method is used to get the persistent instance of the given entity class. The id is the primary key (identifier) of the entity. Method assumes that the entity is existing and if there is not entity then this method is throws the exception "No row with the given identifier exists".

So, if you are using this method add the exception handling mechanism.

There another load() method which takes the LockOptions as parameter. You can use this method to load an entity with the lock options.

Here is the detail of the method:

load(Class theClass, Serializable id, LockOptions lockOptions)

This method is also taking LockOptions as parameter and then returns the entity in the specified lock mode. This method is also assuming that the entity is existing. If no data found than the exception is thrown which must be handled.

Here is an example of using the session.load() method to load entity in Hibernate program:

package net.roseindia;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import net.roseindia.model.*;
/**
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
 */

public class LoadExample {
	public static void main(String[] args) throws Exception {

		SessionFactory sessFact = HibernateUtil.getSessionFactory();
		Session session = sessFact.getCurrentSession();
		org.hibernate.Transaction tr = session.beginTransaction();
		Employee emp = (Employee)session.load(Employee.class, 1);
		System.out.println(emp.getId());
		System.out.println(emp.getEmpName());
		System.out.println(emp.getEmpMobileNos());

		tr.commit();
		System.out.println("Data displayed");
		sessFact.close();
	}
}


It you run the example it will load the Employee entity and display the data on console.

Here is the complete code for saving the data in Hibernate based application:

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import net.roseindia.model.*;
/**
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
 */
public class CreateData {
	public static void main(String[] args) throws Exception {

		SessionFactory sessFact = HibernateUtil.getSessionFactory();
		Session session = sessFact.getCurrentSession();
		org.hibernate.Transaction tr = session.beginTransaction();
		Employee emp = new Employee();
		emp.setEmpName("Deepak Kumar");
		emp.setEmpMobileNos("000000");
		emp.setEmpAddress("Delhi - India");
		session.save(emp);
		tr.commit();
		System.out.println("Successfully inserted");
		sessFact.close();
	}

}

Above class creates the object of Employee entity, sets the values and finally calls the session.save(emp)  to save the data.

Here is the code of the model class used in the example:

package net.roseindia.model;
import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import javax.persistence.Table;
/**
 * @author Deepak Kumar
 * Web: http://www.roseindia.net
 */
@Entity
@Table(name = "employee")
public class Employee implements Serializable{

	@Id
	@GeneratedValue
	@Column(name="id")
	private int id;	

	@Column(name="emp_name")
	private String empName;

	@Column(name="emp_address")
	private String empAddress;	  

	@Column(name="emp_mobile_nos")
	private String empMobileNos;

	public int getId() {
		return id;
	}

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

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getEmpAddress() {
		return empAddress;
	}

	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;
	}

	public String getEmpMobileNos() {
		return empMobileNos;
	}

	public void setEmpMobileNos(String empMobileNos) {
		this.empMobileNos = empMobileNos;
	}

}

The code of hibernate.cfg.xml file used in the project:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate4</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.current_session_context_class">thread</property>

<mapping class="net.roseindia.model.Employee" />

</session-factory>
</hibernate-configuration>

Here is the code of utility class which contains a method to get the SessionFactory:

package net.roseindia;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
 */
public class HibernateUtil {
	private static final SessionFactory sessionFactory;

	private static ServiceRegistry serviceRegistry;

	static {

		try {

			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		} catch (Throwable th) {

			System.err.println("Enitial SessionFactory creation failed" + th);

			throw new ExceptionInInitializerError(th);

		}

	}

	public static SessionFactory getSessionFactory() {

		return sessionFactory;

	}
}

In this you have learned how to use Hibernate's session.save() method to save the data in our example program.

Download the Source code of the project discussed here.

Check more Hibernate 4.2 tutorials.

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 20, 2013

Ask Questions?    Discuss: Hibernate Load Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com