Student.java (POJO)
(This pojo we will use for rest of examples)
package javafiles;
public class Student {
private int rollNumber;
private String name;
private String address;
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Student.hbm.xml
(This .hbm.xml we will use for rest of examples)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="javafiles.Student" table="STUDENTS_DATA">
<id name="rollNumber" column="ROLL_NUMBER" >
<generator class="assigned" />
</id>
<property name="name" column="NAME" length="20"/>
<property name="address" />
</class>
</hibernate-mapping>
Hibernate.cfg.xml
<?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>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
HibernateEngine.java
(This .java we will use for rest of examples)
1) package javafiles;
2) import org.hibernate.*;
3) import org.hibernate.cfg.*;
4) public class HibernateEngine {
5) public static void main(String[] javaPlanet)
6) {
System.out.println("*********START********");
7) Configuration configurationObj = new Configuration();
8) configurationObj.configure("hibernate.cfg.xml");
9) SessionFactory sessionFactoryObj= configurationObj.buildSessionFactory();
10) Session sessionObj = sessionFactoryObj.openSession();
11) Object tempObj=sessionObj.load(Student.class, new Integer(10));
12) Student studentObj=(Student)tempObj;
13) System.out.println("***** Student Data ******\n");
14) System.out.println("Roll Number : "+studentObj.getRollNumber());
15) System.out.println("Name : "+studentObj.getName());
16) System.out.println("Address : "+studentObj.getAddress());
17) sessionObj.close();
18) sessionFactoryObj.close();
19) System.out.println("************END************");
20) }