Hibernate

  • There are 2 ways to configure Hibernate
    • XML
      • Traditional way of configuring Spring and Hibernate
      • We create xml file and create bean tags to configure hibernate and Spring
    • Java Configuration
      • We configure using annotations.
      • Less code needs to be written
XML Configuration
  • Hibernate in Struts is configured as follows in hibernate Configuration file.
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
     "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
      <session-factory>  
           <property name="hibernate.dialect">  
                org.hibernate.dialect.MySQLDialect  
           </property>  
           <property name="hibernate.connection.driver_class">  
                com.mysql.cj.jdbc.Driver  
           </property>  
           <property name="hibernate.connection.url">  
           jdbc:mysql://127.0.0.1:3308/socialnetwork  
           </property>  
           <property name="hibernate.connection.username">  
           root  
           </property>  
           <property name="hibernate.connection.password">  
           </property>  
           <mapping class="com.javaimplant.socialnetwork.model.User"/>  
      </session-factory>  
 </hibernate-configuration>  
  • Hibernate entities are represented as follows
 package com.javaimplant.socialnetwork.model;  
 import javax.persistence.Column;  
 import javax.persistence.Entity;  
 import javax.persistence.GeneratedValue;  
 import javax.persistence.Id;  
 import javax.persistence.Table;  
 import org.hibernate.annotations.GenericGenerator;  
 @Entity  
 @Table(name="users")  
 public class User {  
      @Id  
      @Column(name="Id")  
      @GenericGenerator(name="inc",strategy = "increment")  
      @GeneratedValue(generator = "inc")  
      private Integer id;  
      @Column(name="name")  
      private String userName;  
      @Column(name="password")  
      private String password;  
      public Integer getId() {  
           return id;  
      }  
      public void setId(Integer id) {  
           this.id = id;  
      }  
      public String getUserName() {  
           return userName;  
      }  
      public void setUserName(String userName) {  
           this.userName = userName;  
      }  
      public String getPassword() {  
           return password;  
      }  
      public void setPassword(String password) {  
           this.password = password;  
      }  
 }  
  • Hibernate DAO needs to be configured as follows
    • Session Factory is used to configure hibernate and create our session.
    • Session is used to communicate with hibernate and insert things into the database and getting things from database.
 package com.javaimplant.socialnetwork.dao;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.cfg.Configuration;  
 import com.javaimplant.socialnetwork.model.User;  
 public class UserDAO {  
      private SessionFactory factory;  
      private Session session;  
      public UserDAO()  
      {  
           factory=new Configuration().configure().buildSessionFactory();  
           session=factory.openSession();  
      }  
      public void insertUser(User user)  
      {  
           session.beginTransaction();  
           session.save(user);  
           session.getTransaction().commit();  
      }  
      public void close()  
      {  
           session.close();  
           factory.close();  
      }  
 }  

Entity Manager Factory
  • One persistent factory per unit.
  • Heavyweight and thread safe
  • Created by persistence.createEntityManagerFactory(“”)
Entity Manager
  • An entity manager interface is an API that manages life-cycle of entity instances.
    • Create and remove persistent entity instances
    • Find entity by their primary key
    • Query over entities
  • An entity manager instance manages a set of entities that are defined by a persistence unit.
  • The entity manager tracks All entity object for changes and synchronise the changes with database.
  • Use as a general purpose, DAO interface without specific repository interface.
  • We can use entity Manager in Repository layer, Service layer, controller layer of the application.
  • For DB related operation.
  • Not heavy weight
  • Not thread safe
  • emf.CreateEntityManager();
Persistence Lifecycle
  • We create an object using new keyword.
    • It is in transient state.
  • We use em.persist() to persist object, it moves to persistent state.
  • We use em.detach() to detach object from session, it moves to detached state.
  • We use em.remove() To remove an object from database.
Persistence context
  • Entity Manager Uses persistence context to perform different operations on database.
    • The operations can be persist, find, detach, attach, merge, refresh
  • These methods are called an instance of entity, Manager
  • Entity Manager interact with persistence context to Call, different methods On entities, and as a result of those method calls The result is executed on entities.
  • Persistence context is used to manage life cycle and states of different entities And as a result of those method calls, the result is executed in entities 
  • Assistance context is used to manage life-cycle and states of different entities.
    • It can be a cache or HashMap.
  • JPA creates new instance of persistence context on heap.
  • Persistence context works with the database entities.
  • Entity First goes into persistent context and hibernate decides what to do with entity.
  • When we find an entity ID, if the entity is there in the persistence context, it is returned else, hibernate fetches form DB.
  • Refresh method resets the entity To the last stable state. And entity may be passed down many functions and maybe get changed in database.
  • Merge method update the entity into database, it Apply the changes of persistence context to the entity in database.
    • This is the reverse of refresh method
  • To detach an entity from persistence context, we use detach method.
    • Hibernate does not track such entities anymore.

No comments:

Post a Comment

Spring Boot

What is circular/cyclic dependency in spring boot? When two services are interdependent on each other, that is to start one service, we requ...