Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Saturday, 15 February 2014

Transient, Persistence and Detached Objects in Hibernate

0 comments

While an entity class is created to create a database table or an entity, it is done by making an instance of the entity class and by assigning this instance to the session instance, database table schema is added or updated into the database and a table entry is made. Once the session transaction is saved, it is required to release the entity class instance. These three states of object are classified into their specific categories as Transient, Persistence and Detached object. This article will dictate these all three states of an entity class and will go with an example on this.

Transient, Persistence and Detached Objects in Detail:
Once an entity class has been created to create a database entity or table, it is required to connection with the hibernate and database using SessionFactory and its set of classes. Once the connection configuration is done, we are required to create an instance of the entity class. This state of instance is known as Transient Object.To save the entity class instance into the database, we are required to create a Session class instance that will use the method save() to save the entity class instance into the database. This configuration of the entity class instance is known as Persistence Object.It is necessary to close the session instance after performing the database task. Once a session instance is closed, the state of entity class instance is set to Detached Object.

Let’s go with an example that will dictate the use of transient, persistence and detached object as started with Listing 1:

Listing 1: UserDetails.java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
public class UserDetails {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private intuserId;
    private String userName;
    public intgetUserId() {
        return userId;
    }
    public void setUserId(intuserId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}
Listing 2: AddRecords.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class AddRecords {
    public static void main(String[]args){
        SessionFactorysessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
         
        //To create data
        for(int i = 0; i < 10; i++){
            UserDetails user = new UserDetails();//Creating Transient Object
            user.setUserName("user" + i); //Setting up values to the transient object
            session.save(user);//Updating the transient object to persistnence object
        }
         
        session.getTransaction().commit();
        session.close(); //Session is closed
    }
}
A new instance of a a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate:

Person person = new Person();
person.setName("Foobar");

// person is in a transient state
A persistent instance has a representation in the database, an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session:

Long id = (Long) session.save(person);
// person is now in a persistent state
Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn't attached to a Session anymore (but can still be modified and reattached to a new Session later though).

Monday, 1 April 2013

SpringMVC3 Hibernate CRUD

8 comments
Simple CRUD application using SpringMVC3, Hibernate and MySQL.
Our Application is ContactsManagements where you can view or search contacts, create new contacts, edit or delete existing contacts.

 Step#1: Create the CONTACTS Table
DROP TABLE IF EXISTS `test`.`contacts`;
CREATE TABLE  `test`.`contacts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `address` varchar(45) DEFAULT NULL,
  `gender` char(1) DEFAULT 'M',
  `dob` datetime DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `mobile` varchar(15) DEFAULT NULL,
  `phone` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;

Step#2: Put the SpringMVC, Hibernate and their dependent jars into WEB-INF/lib folder.

Step#3: Configure SpringMVC a) Configure DispatcherServlet in web.xml

  SpringMVCHibernate
  
  
    index.jsp
  
  
  
  dispatcher
  org.springframework.web.servlet.DispatcherServlet
  1
 
 
 
  dispatcher
  *.do
 

 
  org.springframework.web.context.ContextLoaderListener
 
 
     contextConfigLocation
     classpath:applicationContext.xml
  
  
b) dispatcher-servlet.xml

 
 
 

Step#4: Configure JDBC connection parameters and Hibernate properties in config.properties
################### JDBC Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=youbusk


################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
#hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true
Step#5: Configure DataSource, SessionFactory, TransactionManagement support in applicationContext.xml

 
 
 
 
 
  
 
 
 
    
     
 
    
    
 
 
     
     
               
             ${hibernate.dialect}          
             ${hibernate.show_sql}
        
     
  
 
  
 
   
 

Step#6: Configure the Labels, error messages in WEB-INF/classes/Messages.properties
App.Title=Spring MVC - Hibernate CRUD
typeMismatch.java.util.Date=Invalid Date.
dob=DOB


Step#7: Create the Entity class Contact.java
package com;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.apache.commons.lang.builder.ToStringBuilder;



@Entity
@Table(name="CONTACTS")
public class Contact
{
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private int id;
 @Column private String name;
 @Column private String address; 
 @Column private String gender; 
 @Column private Date dob; 
 @Column private String email;
 @Column private String mobile; 
 @Column private String phone;
 
 public Contact()
 {
 }
 
 public Contact(int id, String name, String address, String gender,
   Date dob, String email, String mobile, String phone)
 {
  super();
  this.id = id;
  this.name = name;
  this.address = address;
  this.gender = gender;
  this.dob = dob;
  this.email = email;
  this.mobile = mobile;
  this.phone = phone;
 }
 @Override
 public String toString()
 {
  return ToStringBuilder.reflectionToString(this);
 }
 public int getId()
 {
  return id;
 }
 public void setId(int id)
 {
  this.id = id;
 }
 public String getName()
 {
  return name;
 }
 public void setName(String name)
 {
  this.name = name;
 }
 public String getAddress()
 {
  return address;
 }
 public void setAddress(String address)
 {
  this.address = address;
 }
 public String getGender()
 {
  return gender;
 }
 public void setGender(String gender)
 {
  this.gender = gender;
 }
 public Date getDob()
 {
  return dob;
 }
 public void setDob(Date dob)
 {
  this.dob = dob;
 }
 public String getEmail()
 {
  return email;
 }
 public void setEmail(String email)
 {
  this.email = email;
 }
 public String getMobile()
 {
  return mobile;
 }
 public void setMobile(String mobile)
 {
  this.mobile = mobile;
 }
 public String getPhone()
 {
  return phone;
 }
 public void setPhone(String phone)
 {
  this.phone = phone;
 } 
}
Step#8: Create the ContactsDAO.java which performs CRUD operations on CONTACTS table.
package com;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Harit
 *
 */
@Repository
@Transactional
public class ContactsDAO
{
 @Autowired
 private SessionFactory sessionFactory;
 
 public Contact getById(int id)
 {
  return (Contact) sessionFactory.getCurrentSession().get(Contact.class, id);
 }
 
 @SuppressWarnings("unchecked")
 public List searchContacts(String name)
 {
  Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
  criteria.add(Restrictions.ilike("name", name+"%"));
  return criteria.list();
 }
 
 @SuppressWarnings("unchecked")
 public List getAllContacts()
 {
  Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
  return criteria.list();
 }
 
 public int save(Contact contact)
 {
  return (Integer) sessionFactory.getCurrentSession().save(contact);
 }
 
 public void update(Contact contact)
 {
  sessionFactory.getCurrentSession().merge(contact);
 }
 
 public void delete(int id)
 {
  Contact c = getById(id);
  sessionFactory.getCurrentSession().delete(c);
 }

}
Step#9: Create ContactFormValidator.java which performs the validations on saving/updating a contact.
package com;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;


/**
 * @author Harit
 *
 */
@Component("contactFormValidator")
public class ContactFormValidator implements Validator
{
 @SuppressWarnings("unchecked")
 @Override
 public boolean supports(Class clazz)
 {
  return Contact.class.isAssignableFrom(clazz);
 }

 @Override
 public void validate(Object model, Errors errors)
 {
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name","required.name", "Name is required.");
 }

}
Step#10: Create ContactsControllers.java which processes all the CRUD requests.
package com;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author Harit
 *
 */

@Controller
public class ContactsControllers
{
 @Autowired
 private ContactsDAO contactsDAO;
 
 @Autowired
 private ContactFormValidator validator;
 
 @RequestMapping("/home")
 public String home()
 {
  return "home";
 }
 
 
 @InitBinder
 public void initBinder(WebDataBinder binder) 
 {
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
  dateFormat.setLenient(false);
  binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
 }
  
 @RequestMapping("/searchContacts")
 public ModelAndView searchContacts(@RequestParam(required= false, defaultValue="") String name)
 {
  ModelAndView mav = new ModelAndView("showContacts");
  List contacts = contactsDAO.searchContacts(name.trim());
  mav.addObject("SEARCH_CONTACTS_RESULTS_KEY", contacts);
  return mav;
 }
 
 @RequestMapping("/viewAllContacts")
 public ModelAndView getAllContacts()
 {
  ModelAndView mav = new ModelAndView("showContacts");
  List contacts = contactsDAO.getAllContacts();
  mav.addObject("SEARCH_CONTACTS_RESULTS_KEY", contacts);
  return mav;
 }
 
 @RequestMapping(value="/saveContact", method=RequestMethod.GET)
 public ModelAndView newuserForm()
 {
  ModelAndView mav = new ModelAndView("newContact");
  Contact contact = new Contact();
  mav.getModelMap().put("newContact", contact);
  return mav;
 }
 
 @RequestMapping(value="/saveContact", method=RequestMethod.POST)
 public String create(@ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status)
 {
  validator.validate(contact, result);
  if (result.hasErrors()) 
  {    
   return "newContact";
  }
  contactsDAO.save(contact);
  status.setComplete();
  return "redirect:viewAllContacts.do";
 }
 
 @RequestMapping(value="/updateContact", method=RequestMethod.GET)
 public ModelAndView edit(@RequestParam("id")Integer id)
 {
  ModelAndView mav = new ModelAndView("editContact");
  Contact contact = contactsDAO.getById(id);
  mav.addObject("editContact", contact);
  return mav;
 }
 
 @RequestMapping(value="/updateContact", method=RequestMethod.POST)
 public String update(@ModelAttribute("editContact") Contact contact, BindingResult result, SessionStatus status)
 {
  validator.validate(contact, result);
  if (result.hasErrors()) {
   return "editContact";
  }
  contactsDAO.update(contact);
  status.setComplete();
  return "redirect:viewAllContacts.do";
 }
 
 
 @RequestMapping("deleteContact")
 public ModelAndView delete(@RequestParam("id")Integer id)
 {
  ModelAndView mav = new ModelAndView("redirect:viewAllContacts.do");
  contactsDAO.delete(id);
  return mav;
 }
 
}
Step#11: Instead of writing the JSTL tag library declerations in all the JSPs, declare them in one JSP and include that JSP in other JSPs. taglib_includes.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
Step#12: Create the JSPs.
a)showContacts.jsp
<%@include file="taglib_includes.jsp" %>




<spring:message code="App.Title"></spring:message> 



 
Enter Contact Name      
Id Name Address Mobile
No Results found
 Edit   Delete
b) newContact.jsp
<%@include file="taglib_includes.jsp" %>



 
 <spring:message code="App.Title"></spring:message> 



Edit Contact Form

Name
DOB
Gender
Address
Email
Mobile
     
c) home.jsp
<%@include file="taglib_includes.jsp" %>


<spring:message code="App.Title"></spring:message> 



 Show Contacts 


 

d) editContact.jsp
<%@include file="taglib_includes.jsp" %>



 
 <spring:message code="App.Title"></spring:message> 



Edit Contact Form

Id
Name
DOB
Gender
Address
Email
Mobile
     
Step#13: Write the javascript file js/contacts.js containing the utility methods
function go(url)
{
 window.location = url;
}

function newContact()
{
 window.location = "saveContact.do";
}

function deleteContact(url)
{
 var isOK = confirm("Are you sure to delete?");
 if(isOK)
 {
  go(url);
 }
}

Download Complete Project
Related Posts Plugin for WordPress, Blogger...