Monday, February 7, 2011

Simple Hibernate Code

1. Create a project in eclipse.
2. Place the hibernate jars in the lib folder from www.hibernate.org
Hello Hibernate:

Web.xml
<?xml version="1.0" encoding="UTF-8"?>

             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             version="2.4">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
            <welcome-file>
            index.jsp
        </welcome-file>
    </welcome-file-list>
</web-app>

Index.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%--
The taglib directive below imports the JSTL library. If you uncomment it,
you must also add the JSTL library to the project. The Add Library... action
on Libraries node in Projects view can be used to add the JSTL 1.1 library.
--%>
<%--
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
--%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>

    <h1>JSP Page</h1>
   
    <%--
    This example uses JSTL, uncomment the taglib directive above.
    To test, display the page like this: index.jsp?sayHello=true&name=Murphy
    --%>
    <%--
    <c:if test="${param.sayHello}">
        <!-- Let's welcome the user ${param.name} -->
        Hello ${param.name}!
    </c:if>
    --%>
   
    </body>
</html>

Details.xml (should be in default package)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping>
  <class name="mypackage.Details" table="hibernateTable">
   <id name="id" type="int" column="id" >
   <generator class="assigned"/>
  </id>

  <property name="firstName">
     <column name="firstname" />
  </property>
  <property name="lastName">
    <column name="lastname"/>
  </property>
  <property name="middleName">
    <column name="middlename"/>
  </property>
 </class>
</hibernate-mapping>

Hibernate.cfg.xml (should be in default package)
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
<hibernate-configuration>
<session-factory>
      <property name="hibernate.connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
      <property name="hibernate.connection.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test</property>
      <property name="hibernate.connection.username">sa</property>
      <property name="hibernate.connection.password">sa</property>
      <property name="hibernate.connection.pool_size">10</property>
      <property name="show_sql">true</property>
      <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <!-- Mapping files -->
      <mapping resource="details.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Details.java
package mypackage;

public class Details {
   
  private String firstName;
  private String middleName;
  private String lastName;
  private int iD;

  public int getId() {
    return iD;
  }
  public String getFirstName() {
    return firstName;
  }

  public String getMiddleName() {
    return middleName;
  }

  public String getLastName() {
    return lastName;
  }

   public void setId(int in) {
    iD = in;
  }
  
  public void setFirstName(String string) {
    firstName = string;
  }

   public void setMiddleName(String string) {
    middleName = string;
  }
  public void setLastName(String string) {
    lastName = string;
  }
}

FirstExample.java
package mypackage;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Transaction;



public class FirstExample {
  public static void main(String[] args) {
    Session session = null;
     Details contact = new Details();
    
    try{
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session =sessionFactory.openSession();
        System.out.println("Inserting Record");
        Transaction tx = session.beginTransaction();
      
         int i=100000;
        contact.setId(i++);
        contact.setFirstName("Harshal");
        contact.setLastName("Shah");
        contact.setMiddleName("Dilip");
        session.save(contact);
        System.out.println("Done");
        System.out.print(""+contact.getId());
        System.out.println(contact.getFirstName());
      //  session.update(contact);
       
      //  session.contains(contact);
        tx.commit();
       // session.flush();
       
    }catch(Exception e){
      System.out.println(e.getMessage());
    }finally{
      // Actual contact insertion will happen at this step
      session.flush();
      session.close();

      }
   
  }
}

No comments:

Post a Comment