Choose Your Language

Friday, 20 November 2015

Hibernate integration for insert, update, retrive and delete records in a table using JPA Annotations

Project Structure



Create a database with name retailer 

create database retailer;
use retailer;

Create a table with name users

DROP TABLE IF EXISTS `retailer`.`users`;
CREATE TABLE  `retailer`.`users` (
  `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uname` varchar(45) DEFAULT NULL,
  `upassword` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`uid`)
);


Users.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernateannotaionexample;

import java.io.Serializable;
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 javax.persistence.UniqueConstraint;

/**
 *
 * @author Aravind Sankaran Nair
 */
@Entity 
@Table(name = "users", catalog = "retailer", uniqueConstraints = {@UniqueConstraint(columnNames = "uname"),@UniqueConstraint(columnNames = "upassword")})
public class Users implements Serializable {
   
    private int UID;
    private String UNAME;
    private String UPASSWORD;
    public Users(){
        
    }
    public Users(String UNAME,String UPASSWORD){        
        this.UNAME=UNAME;
        this.UPASSWORD=UPASSWORD;
    }
    public Users(int UID,String UNAME,String UPASSWORD){
        this.UID=UID;
        this.UNAME=UNAME;
        this.UPASSWORD=UPASSWORD;
    }
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column(name = "uid", nullable = false, unique = true)
    public int getUID() {
        return UID;
    }
    public void setUID(int UID) {
        this.UID = UID;
    }
    @Column(name = "uname", nullable = false, unique = true, length = 45)
    public String getUNAME() {
        return UNAME;
    }

    public void setUNAME(String UNAME) {
        this.UNAME = UNAME;
    }
    @Column(name = "upassword", nullable = false, unique = true, length = 45)
    public String getUPASSWORD() {
        return UPASSWORD;
    }

    public void setUPASSWORD(String UPASSWORD) {
        this.UPASSWORD = UPASSWORD;
    }
}


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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/retailer</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="hibernateannotaionexample.Users"></mapping>
  </session-factory>
</hibernate-configuration>


Operations.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernateannotaionexample;

import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class Operations {
    Session session=null;
    SessionFactory sessionFactory =new AnnotationConfiguration().configure().buildSessionFactory();
    public void insertData(String userName,String userPassword){
        session=sessionFactory.openSession();
        session.beginTransaction();
        Users user=new Users();
        user.setUNAME(userName);
        user.setUPASSWORD(userPassword);
        session.save(user);
        session.getTransaction().commit();        
    }
    
    public void updateRecord1(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="From Users where UID= :uid";
        Query query=session.createQuery(SQL_QUERY);
        query.setParameter("uid", UID);
        for(Iterator it=query.iterate();it.hasNext();){
        Users u=(Users)it.next();
        u.setUNAME("meera");
        u.setUPASSWORD("sankar");
        session.update(u);
        }
        session.getTransaction().commit();
    }
    public void updateRecord2(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();       
        String SQL_QUERY="FROM Users where UID="+UID;        
        Query query=session.createQuery(SQL_QUERY);
        for(Iterator it=query.iterate();it.hasNext();){
        Users u=(Users)it.next();
        
        u.setUNAME("meera");
        u.setUPASSWORD("meera");
        session.update(u);
        }
        session.getTransaction().commit();
    }
    public void showAllRecord(){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users";
        Query query=session.createQuery(SQL_QUERY);
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            System.out.println("UID="+u.getUID());
            System.out.println("UNAME="+u.getUNAME());
            System.out.println("UPASSWORD="+u.getUPASSWORD());
        }
        session.getTransaction().commit();
    }
    public void showParticularRecord1(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users where UID= :uid";
        Query query=session.createQuery(SQL_QUERY);
        query.setParameter("uid", UID);
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            System.out.println("UID = "+u.getUID());
            System.out.println("UNAME = "+u.getUNAME());
            System.out.println("UPASSWORD = "+u.getUPASSWORD());
        }
        session.getTransaction().commit();
    }
    public void showParticularRecord2(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();        
        String SQL_QUERY="FROM Users where UID="+UID;        
        Query query=session.createQuery(SQL_QUERY);       
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            System.out.println("UID = "+u.getUID());
            System.out.println("UNAME = "+u.getUNAME());
            System.out.println("UPASSWORD = "+u.getUPASSWORD());
        }
        session.getTransaction().commit();
    }
    public void deleteParticularRecord1(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users where UID= :uid";
        Query query=session.createQuery(SQL_QUERY);
        query.setParameter("uid", UID);
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            session.delete(u);
        }
        session.getTransaction().commit();
    }
    public void deleteParticularRecord2(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users where UID="+UID;        
        Query query=session.createQuery(SQL_QUERY);       
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            session.delete(u);
        }
        session.getTransaction().commit();
    }
    public void deleteALLRecord(){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users";        
        Query query=session.createQuery(SQL_QUERY);       
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            session.delete(u);
        }
        session.getTransaction().commit();
    }
}


HibernateAnnotaionExample.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernateannotaionexample;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class HibernateAnnotaionExample {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Operations operations=new Operations();
        /*insert data to user table*/
        operations.insertData("aravind", "aravind");
        operations.insertData("sreeja", "damodaran");
        operations.insertData("jayesh", "babu");
        operations.insertData("bento", "rajan");
        /*update data of user table with UID value*/
        operations.updateRecord1(21);
        operations.updateRecord2(22);
        /*retrive data from user table*/
        operations.showAllRecord();
        operations.showParticularRecord1(22);
        operations.showParticularRecord2(23);
        /*delete user table records*/
        operations.deleteParticularRecord1(21);
        operations.deleteParticularRecord2(21);
        operations.deleteALLRecord();
    }
}


Jar Files Needed

hibernate
persistence
mysql-connector-java-5.1.18-bin.jar

No comments:

Post a Comment