Tuesday, June 11, 2013

06 - Retrieving-Objects-using-session-get



Different between session.get() and session.load()?
session.get()
It always hit the database and returns the real object, an object that represents the database row, not proxy.  If no row found, it return null. Method is used to process only one record at a time.

session.load()
It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object. If no row found, it will throws an ObjectNotFoundException.

session.close(); It is like a finally block.

After session close you need to open new session to fetch new object

Session factory created only once per application because it is very expensive object it takes lot of resources to create so it is better to have one object in your application and that one object is used to create session in your application.

In later sessions we see how session factory object accessed across different layer.

To retrive the object from DB.
user = null;
session = sessionFactory.openSession();
session.beginTransaction();
user = (UserDetails)session.get(UserDetails.class,1);
System.out.println("User Name retrieved is "+user.getUserName());
UserDetails.class is the class for which we are fetching the data
1-> is the primarykey i.e. userId.

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">
            org.postgresql.Driver
        </property>
        <property name="connection.url">
            jdbc:postgresql://localhost:5433/hibernatedb
        </property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">admin</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">
            org.hibernate.dialect.PostgreSQLDialect
        </property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
       
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
       
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property> 
        <!-- create / update -->
   
          <!-- Names the annotated entity class -->
            <mapping class="org.yash.dto.UserDetails"/>    

    </session-factory>

</hibernate-configuration>

UserDetails.java
package org.yash.dto;

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
      /* @Id says "userId" is primary key */
      @Id
      private int userId;    
      private String userName;
      private Date joinedDate;
      private String Address;
      private String description;
     
      public int getUserId() {
            return userId;
      }
      public void setUserId(int userId) {
            this.userId = userId;
      }
      public String getUserName() {
            return userName;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }

      public Date getJoinedDate() {
            return joinedDate;
      }
      public void setJoinedDate(Date joinedDate) {
            this.joinedDate = joinedDate;
      }
      public String getAddress() {
            return Address;
      }
      public void setAddress(String address) {
            Address = address;
      }
      public String getDescription() {
            return description;
      }
      public void setDescription(String description) {
            this.description = description;
      }
}

HibernateTest.java
package org.yash.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.yash.dto.UserDetails;

public class HibernateTest {

      public static void main(String args[]){
            UserDetails user = new UserDetails();
            user.setUserId(1);
            user.setUserName("Third User");
            user.setAddress("Bentonville");
            user.setJoinedDate(new Date());
            user.setDescription("Description of user goes here");
           
            SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
           
            Session session = sessionFactory.openSession();
            session.beginTransaction();
           
            session.save(user);
            session.getTransaction().commit();
           
            user = null;
           
            session = sessionFactory.openSession();
            session.beginTransaction();
            user = (UserDetails) session.get(UserDetails.class, 1);
           
            if(user != null){
                  System.out.println("User name retrieved is
                                     "+user.getUserName());
            }else{
                  System.out.println("No Records");                    
            }

      }
}

No comments:

Post a Comment