Wednesday, 5 December 2012

Simple Hibernate example

Simple Hibernate example

Here i am created  a simple hibernate example which include all the pojo,orm and hibernate-configuration


package com.nik.test

public class StudentInfo implements java.io.Serializable {

    private long studentId;
    private String studentName;

    public Student() {
    }

    public StudentInfo(String studentName) {
        this.studentName = studentName;
    }

    public long getStudentId() {
        return this.studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return this.studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

}




The ORM(object relational mapping) file is as follows:
Student.hbm.xml



<?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="com.nik.test.StudentClass" table="STUDENT">
    <meta attribute="class-description">
    This class contains the course details.
    </meta>
    <id name="studentId" type="long" column="studentID">
        <generator class="native"/>
    </id>
    <property name="studentName" type="string" column="studentName" not-null="true" />
</class>


</hibernate-mapping>




Hibernate configuration file is as follows:

hibenate.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 name="">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost/testdb</property>
  <property name="hibernate.connection.username">root</property>
  <property name="connection.password"></property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hbm2ddl.auto">create</property>
  <mapping class="com.nik.test.StudentInfo" />
   
 </session-factory>
</hibernate-configuration>