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.

Advertisements

6 Responses to My First Hibernate Example

  1. Ajay Patel says:

    like this brother …..

  2. ashok says:

    hi,bro
    i am a big fan of you. realy u great
    plz send me advice to improve my java skills
    i am new in java
    plz help me

    • Prashant says:

      What I would like to suggest you is, Clear your oops and core java concepts.
      Then after that go threw some projects. It will help you to implement the concepts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: