Friday, 23 September 2016

Hibernate ORM

  • Persistence 
    • The state of an object can be saved to  a data store, and recreated at a later point in time. It can be persisted to a file or a db.
  • ORM
    • Object Relational mapping
    • It refers to the technique of mapping the representation of data from Java Objects to Relational Database (and vice versa).
  • Hibernate
    • Object Relational mapping solution for Java
    • Framework for mapping Object model to Relational databases
    • It maps Java data types to Database specific data types
    • Generates sql queries automatically and hence, reduces the development time
    • Database independent - can switch to different DB by editing single configuration file
    • Communication happens between Java -> Hibernate -> DB, and vice versa
  • Setup Steps
    • 1. Download hybernate orm zip from http://hibernate.org/
    • 2. Create lib directory in the project, copy jars from downloaded zip lib folders -> required, jpa, java8 directories to project lib folder in eclipse
    • 3. Copy jdbc driver into project lib folder
    • 4. Add jar to class path
        project properties -> build path -> libraries -> add jars
  • Hibernate configuration
    • 1. Add hibernate configuration file to src directory hibernate.cfg.xml
      <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

      <hibernate-configuration>
          <session-factory>
              <!-- JDBC Database connection settings -->
              <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
              <property name="connection.url">jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=SLC03RYC.us.oracle.com)(PORT=1521)) (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=xe)))</property>
              <property name="connection.username">vdesu</property>
              <property name="connection.password">vdesu</property>

              <!-- JDBC connection pool settings ... using built-in test pool -->
              <property name="connection.pool_size">1</property>

              <!-- Select our SQL dialect -->
              <property name="dialect">org.hibernate.dialect.OracleDialect</property>

              <!-- Echo the SQL to stdout -->
              <property name="show_sql">true</property>

              <!-- Set the current session context -->
              <property name="current_session_context_class">thread</property>

          </session-factory>
      </hibernate-configuration>
    • Annotate java class(mapping class to db table).  Entity class - Java class that is mapped to a database table
      • Option 1: XML config file (legacy)
      • Option 2: Java annotations (modern, preferred)
        • @Entity
          @Table(name="student")
        •     @Id
              @Column(name="id")
        •     @Column(name="first_name")
    •  Develop java code to perform database operations
      • package com.luv2code.hibernate.demo;

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

        import com.luv2code.hibernate.demo.entity.Student;

        public class CreateStudentDemo {

            public static void main(String[] args) {
               
                SessionFactory factory = new Configuration()
                                        .configure("hibernate.cfg.xml")
                                        .addAnnotatedClass(Student.class)
                                        .buildSessionFactory();
               
                Session session = factory.getCurrentSession();

              try{
                Student tempStudent = new Student("venkat","desu","venkat.desu@gmail.com");
                 session.beginTransaction();
                session.save(tempStudent);
                session.getTransaction().commit();
                System.out.println("done");
            } finally {
                factory.close();
            }
               

            }

        }
    • Execute the program.
  • Retrieve a java object with hibernate
    • Student mystudent=session.get(Student.class, <ID value>);
  • Retrieve all Students using Hibernate Query Language (HQL)
    • List<Student> theStudents = session.createQuery("from Student").list();
    • List<Student> theStudents = session.createQuery("from Student s where s.lastName='desu'").list();
    •  List<Student> theStudents = session.createQuery("from Student s where s.lastName='desu' OR s.firstName='venkat'").list();
    • List<Student> theStudents = session.createQuery("from Student s where s.lastName like 'desu%'").list(); 
  • Update Object
    • Student mystudent=session.get(Student.class, <ID value>);
      mystudent.setFirstName("asdf");
  • Bulk Update
    •  session.createQuery("update Student set lastName='desu'").executeUpdate();
  • Delete Object
    • Student mystudent=session.get(Student.class, <ID value>);
      session.delete(mystudent);
  • Bulk Delete
    •  session.createQuery("delete from Student where id=0").executeUpdate();
Hibernate Query Language:
  • HQL is an Object Oriented Query Language
  • Unlike SQL, HQL uses/operates on Classes instead of Tables
  • Advantages
    • Database independent - Easy migration from one DB to another
    • Easy for Java programmers - Quick to learn and implement
  • Creating Tables with Primary and foreign key
Hibernate Object States & LifeCycle:
  • Transient 
    • It is just a POJO Object eg: Student Object
  • Persistent -> Transient Object have association with table. Starts once Transaction is started. The state ends with Commit()
    • session.save()
    • session.persist()
    • session.saveOrUpdate() 
    • session.load()
    • session.get()
    • session.byId()
    • session.byNaturalId()
  • Detached - starts with one of the following methods
    • session.evict() - evicts from session
    • session.clear()
    • session.close() 
    • We can move from detached to Persistent using update(), merge(), saveOrUpdate()
    • It not used then it will be removed by garbage collector
  • Removed
      • session.delete() 
      • It will be available for garbage collection and cannot be used
JPA vs Hibernate(Entity Manger vs Session)


No comments:

Post a Comment