hibernate by example

In this tutorial you will learn hibernate by example with ready made downloadable source code.


 

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

hibernate by example

In this tutorial you will learn hibernate by example with ready made downloadable source code.

Here I am giving an example which will demonstrate you how can you make your application using Hibernate 4. To create an application I will use Eclipse IDE ( to see the basic requirement before creating an application with Hibernate 4 click here ).

Example :

Following steps that I have followed to create an application. These are as follows :

Step 1 : At first I have created a table named person in MySQL.

CREATE TABLE `person` ( 
`Id` int(10) NOT NULL, 
`Name` varchar(15) default NULL, 
PRIMARY KEY (`Id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

Step 2 : Created a Java Project named coreHibernateExample (you can give the name as you wish).

File -> New -> project / Java Project -> giveProjectName -> Finish (in this example I have given coreHibernateExample).

Step 3 : Add the Hibernate jar files (to see how to add Hibernate's jar files click here )

Step 4 : Created a package named roseindia (you can give the name as you wish) under the src folder.

Select src -> Right Click ->New -> package -> givePackageName -> Finish (in this exmaple I have given roseindia).

Ste 5 : Created a file by following the name convention hibernate.cfg.xml (mandatory ) file under the src folder that the hibernate utilize to create a connection pool and the required environment setup.

Select src -> Right Click -> New -> File ->hibernate.cfg.xml -> Finish.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/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://192.168.10.13:3306/data
</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>

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

Step 6 : Created a POJO class (persistent class) named Person.java in the package roseindia.

package roseindia;

public class Person
{
int id;
String name;
public Person()
{ 
}
public Person(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Step 7 : Crated a file named ( you may follow the naming convention ClassName.hbm.xml )  person.hbm.xml under the src folder to map a Person Object to the database table named person

<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">
<class name="Person" table="person">
<id name="id" type="int" column="Id" >
<generator class="assigned"/>
</id>

<property name="name">
<column name="Name" />
</property>

</class>
</hibernate-mapping>

Step 8 : Developed a code by writing a java class named PersonDetail in the package roseindia which will persist the Person object in the person table.

package roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class PersonDetail
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args)
{
Session session = null;
try 
{
try
{
Configuration cfg = new Configuration().addResource(
"person.hbm.xml").configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex)
{
System.err.println("Failed to create sessionFactory object."+ ex);
throw new ExceptionInInitializerError(ex);
}
session = sessionFactory.openSession();

Person person = new Person();
System.out.println("Inserting Record");
Transaction tx = session.beginTransaction();
person.setId(1);
person.setName("Roseindia");
session.save(person);
tx.commit();
System.out.println("Done");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
session.close();
}
}
}

Execute the example : You can execute the application as follows

Go to your PersonDetail class Right Click -> Run As -> Java Application or,

Select from the menu bar tab Run -> Run or,

press the Ctrl button along with f11 i.e. CTRL + f11.

Output :

When you will run the application output will be as follows :

1. On console of Eclipse the output will be displayed as :

2. After Successfully execution of the code the record will be saved to the table that you had created in MySQL. as :

Download Source Code

Advertisements

Ads
Share on Google+Share on Google+

hibernate by example

Posted on: May 17, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: hibernate by example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads