Tuesday, May 6, 2014

Hibernate HQL CRUD Example

HQLTest.java


package com.pkm.commands;

import com.pkm.domains.User;
import com.pkm.utils.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HQLTest {
    public static void main(String[] args) {
        Session session = null;
     Transaction transaction = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            transaction = session.beginTransaction();
            
            /* INSERT QUERY */
            SQLQuery sQLQuery = session.createSQLQuery("INSERT INTO "
                    + "User(email, first_name, last_name, phone_number, area_code) "
                    + "Values(:email, :first_name, :last_name, :phone_number, :area_code)");
            sQLQuery.setParameter("email", "pritomkucse@gmail.com");
            sQLQuery.setParameter("first_name", "Pritom");
            sQLQuery.setParameter("last_name", "Kumar");
            sQLQuery.setParameter("phone_number", "01727499452");
            sQLQuery.setInteger("area_code", 88);
            int insertResult = sQLQuery.executeUpdate();
            System.out.println("Insert Result: " + insertResult);
            
            /* SELECT QUERY*/
            Query query = session.createQuery("SELECT MIN(id) FROM User");
            query.setMaxResults(1);
            List queryList = query.list();
            System.out.println(queryList);
            
            query = session.createQuery("FROM User");
            query.setMaxResults(5);
            query.setReadOnly(true);
            queryList = query.list();
            for(Object object : queryList) {
                User user = (User) object;
                System.out.println("Email: " + user.getEmail() + ", First Name: " 
                        + user.getFirstName() + ", Last Name: " + user.getLastName() 
                        + ", Phone Area: " + user.getAreaCode() 
                        + ", Phone Number: " + user.getPhoneNumber());
            }
            
            /* UPDATE QUERY */
            User user = (User) queryList.get(0);
            query = session.createQuery("UPDATE User SET email=:email WHERE id = :id");
            query.setParameter("id", user.getId());
            query.setParameter("email", "sdfsdfsdf@gmail.com");
            int updateResult = query.executeUpdate();
            System.out.println("Update Result: " + updateResult);
            
            /* DELETE QUERY */
            user = (User) queryList.get(1);
            query = session.createQuery("DELETE FROM User WHERE id = :id");
            query.setParameter("id", user.getId());
            updateResult = query.executeUpdate();
            System.out.println("Delete Result: " + updateResult);
            
            transaction.commit();
        } catch (Exception ex) {
            if(transaction != null) {
                transaction.rollback();
            }
            System.out.println("Error: " + ex.getMessage());
        } finally {
            if(session != null) {
                session.close();
            }
        }
    }
}


You have to include antlr.jar to use HQL in your hibernate program.

Data saved in database as follows:


The java entity class used for this example:


package com.pkm.domains;

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.Temporal;
import javax.persistence.TemporalType;

@Entity
public class User implements java.io.Serializable {   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;
    public void setId(Long id) {
        this.id = id;
    }
    public Long getId() {
        return this.id;
    }
    
    @Column(name = "email", unique = true, nullable = false, length = 100)
    private String email;
    public void setEmail(String email) {
        this.email = email;
    }
    public String getEmail() {
        return this.email;
    }
     
    @Column(name = "first_name", nullable = false)
    private String firstName;
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getFirstName() {
        return this.firstName;
    }
     
    @Column(name = "last_name", nullable = true)
    private String lastName;
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getLastName() {
        return this.lastName;
    }
     
    @Column(name = "phone_number", nullable = false)
    private String phoneNumber;
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    public String getPhoneNumber() {
        return this.phoneNumber;
    }
     
    @Column(name = "area_code", nullable = true)
    private int areaCode;
    public void setAreaCode(int areaCode) {
        this.areaCode = areaCode;
    }
    public int getAreaCode() {
        return this.areaCode;
    }
    
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "date_updated", unique = false, nullable = true, length = 100)
    private Date dateUpdated;
    public void setDateUpdated(Date dateUpdated) {
        this.dateUpdated = dateUpdated;
    }
    public Date getDateUpdated() {
        return this.dateUpdated;
    }
    
    public User() {
        this.dateUpdated = new Date();        
    }
}

Output as following


Hibernate: INSERT INTO User(email, first_name, last_name, phone_number, area_code) Values(?, ?, ?, ?, ?)
Insert Result: 1
Hibernate: select min(user0_.id) as col_0_0_ from User user0_ limit ?
[14]
Hibernate: select user0_.id as id0_, user0_.date_updated as date2_0_, user0_.email as email0_, user0_.first_name as first4_0_, user0_.last_name as last5_0_, user0_.phone_number as phone6_0_, user0_.area_code as area7_0_ from User user0_ limit ?
Email: sdfsdfsdf@gmail.com, First Name: Pritom, Last Name: Kumar Mondal, Phone Area: null, Phone Number: null
Email: 1399089957760@gmail.com, First Name: First name changed, Last Name: Kumar Mondal, Phone Area: null, Phone Number: null
Email: 1399089987865@gmail.com, First Name: Pritom, Last Name: Kumar Mondal, Phone Area: null, Phone Number: null
Email: 1399089987945@gmail.com, First Name: First name changed, Last Name: Kumar Mondal, Phone Area: null, Phone Number: null
Email: 1399090021059@gmail.com, First Name: Pritom, Last Name: Kumar Mondal, Phone Area: null, Phone Number: null
Hibernate: update User set email=? where id=?
Update Result: 1
Hibernate: delete from User where id=?
Delete Result: 1

Annotating Composite Custom Types in Hibernate

Two new classes are needed. The first is the class you want to use for the column(columns for composite user type).  In my case, I created a class Phone to store data in database.  Here's my class:
package com.pkm.utils;

public class Phone implements java.io.Serializable {
    private Integer areaCode = null;
    public Integer getAreaCode() {
        return areaCode;
    }
    public void setAreaCode(Integer areaCode) {
        this.areaCode = areaCode;
    }
    public void clearAreaCode() {
        this.areaCode = null;
    }
    
    private String phoneNum = null;
    public String getPhoneNum() {
        return phoneNum;
    }
    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }
    
    public Phone() {
        
    }
    
    public Phone(String phoneNum, Integer areaCode) {
        this.phoneNum = phoneNum;
        this.areaCode = areaCode;
    }
    
    public Phone(String phoneNum) {
        this.phoneNum = phoneNum;
        this.areaCode = null;
    }
    
    @Override
    public String toString(){
        return areaCode + "-" + phoneNum;
   }
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((areaCode == null) ? 0 : areaCode.hashCode());
        result = prime * result + ((phoneNum == null) ? 0 : phoneNum.hashCode());
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Phone other = (Phone) obj;
        if (areaCode == null) {
            if (other.areaCode != null)
                return false;
        } else if (!areaCode.equals(other.areaCode))
            return false;
        if (phoneNum == null) {
            if (other.phoneNum != null)
                return false;
        } else if (!phoneNum.equals(other.phoneNum))
            return false;
        return true;
    }
}


The factory class is produced by implementing (in the complex case) org.hibernate.usertype.CompositeUserType, you can also see simple case example. Documentation in this interface is pretty thin, but there are good examples available in the Hibernate distribution. Here's my implementation.

PhoneCompositeType.java

package com.pkm.utils;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;

public class PhoneCompositeType implements CompositeUserType {
    @Override
    public String[] getPropertyNames() {
        return new String[] {"phoneNum", "areaCode"};
    }

    @Override
    public Type[] getPropertyTypes() {
        return new Type[]{
            org.hibernate.type.StandardBasicTypes.STRING,
            org.hibernate.type.StandardBasicTypes.INTEGER
        };
    }

    @Override
    public Object getPropertyValue(Object o, int i) 
            throws HibernateException {
        if(o == null) {
            return null;
        } else if(i == 0) {
            return ((Phone) o).getPhoneNum();
        } else if(i == 1) {
            return ((Phone) o).getAreaCode();
        }
        return null;
    }

    @Override
    public void setPropertyValue(Object o, int i, Object o1) 
            throws HibernateException {
        if(o != null) {
            if(i == 0) {
                ((Phone) o).setPhoneNum((String) o1);
            } else if(i == 1 && o1 != null) {
                ((Phone) o).setAreaCode((Integer) o1);
            }
        }
    }

    @Override
    public Class returnedClass() {
        return Phone.class;
    }

    @Override
    public boolean equals(Object o, Object o1) throws HibernateException {
        if(o == null && o1 == null) {
            return true;
        }
        if(o == null || o1 == null) {
            return false;
        }
        return o.equals(o1);
    }

    @Override
    public int hashCode(Object o) throws HibernateException {
        if(o != null) {
            return o.hashCode();
        }
        return 0;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] strings, 
    SessionImplementor si, Object o) 
            throws HibernateException, SQLException {
        String phoneNum = rs.getString(strings[0]);
        String areaCode = rs.getString(strings[1]);
        if(phoneNum != null) {
            Phone phone = new Phone(phoneNum);
            if(areaCode != null) {
                phone.setAreaCode(Integer.parseInt(areaCode));
            }
            return phone;
        }
        return null;
    }

    @Override
    public void nullSafeSet(PreparedStatement ps, Object o, int i, 
    SessionImplementor si) 
            throws HibernateException, SQLException {
        if(o != null) {
            ps.setString(i, ((Phone) o).getPhoneNum());
            if(((Phone) o).getAreaCode() != null) {
                ps.setInt(i + 1, ((Phone) o).getAreaCode());
            } else {
                ps.setString(i + 1, null);
            }
        } else {
            ps.setString(i, null);
            ps.setString(i + 1, null);
        }
    }

    @Override
    public Object deepCopy(Object o) throws HibernateException {
        if(o != null) {
            Phone newPhone = (Phone) o;
            return new Phone(newPhone.getPhoneNum(), newPhone.getAreaCode());
        }
        return null;
    }

    @Override
    public boolean isMutable() {
        return false;
    }

    @Override
    public Serializable disassemble(Object o, SessionImplementor si) 
            throws HibernateException {
        Object  deepCopy = deepCopy(o);
        if(!(deepCopy instanceof Serializable)) {
            return (Serializable) deepCopy;
        }
        return null;
    }

    @Override
    public Object assemble(Serializable srlzbl, 
    SessionImplementor si, Object o) 
            throws HibernateException {
        return deepCopy(srlzbl);
    }

    @Override
    public Object replace(Object o, Object o1, 
    SessionImplementor si, Object o2) 
            throws HibernateException {
        return deepCopy(o);
    }    
}


The core of this class is the two methods which get and set values associated with my new type: nullSafeSet and nullSafeGet. One key thing to note is that nullSafeGet is supplied with a list of all the column names mapped to the custom datatype in the current query. In my case, there's only one, but in complex cases, you can map multiple columns to one object (there are examples in the Hibernate documentation). The final piece of the puzzle is the annotation which tells Hibernate to use the new "Type" class to generate objects of your custom type by adding a new @Type annotation to the column. There would create two columns in the database as it is composite user type, not simple one. Data saved in database as follows:


Use new type as follows:


@Type(type = "com.pkm.utils.PhoneCompositeType")
@Columns(columns = {
    @Column(name = "phone_number"), 
    @Column(name = "area_code", nullable = true)
})
private Phone phone = new Phone();
public void setPhone(Phone phone) {
    this.phone = phone;
}
public Phone getPhone() {
    if(phone == null) {
        phone = new Phone();
    }
    return phone;
}

Use as follows


User user = (User) session.get(User.class, 1);
user.getPhone().setAreaCode(880);
user.getPhone().setPhoneNum("01727499452");

Output in my database as like (After save/update reading values from database):


Phone area: 880
Phone number: 01727499452

Monday, May 5, 2014

Setting default value for fields in Grails Domain Class


class MyDomainClass {
    Date myDate = new Date();
    Boolean myBoolean = false;
    String myString = "";

    static mapping = {
        myDate defaultValue: "now()"
        myBoolean defaultValue: "false"
        myString defaultValue: ""
    }
}

You can use sql now() method rather than Java/Groovy new Date()

Convert Map, HashMap or List/ArrayList to XML and reverse

HashMapToStringXml.java

package pritom;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pritom on 5/05/14.
 */
public class HashMapToStringXml {
    public static void main(String[] args) {
        Map<Object, Object> hashMap = new HashMap<Object, Object>();
        hashMap.put("firstName", "Pritom");
        hashMap.put("lastName", "Kumar");

        Map<Object, Object> secondMap = new HashMap<Object, Object>();
        secondMap.put("timeIn", "8:00");
        secondMap.put("timeOut", "5:00");
        hashMap.put("timing", secondMap);

        List<Object> list = new ArrayList<Object>();
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(secondMap);
        hashMap.put("contents", list);

        /* Map to XML and reverse */
        String mapToString = objectToString(hashMap);
        Map parsedMap = (Map) stringToObject(mapToString);
        System.out.println("Map to XML: \n" + mapToString + "\nXML to map:\n" + parsedMap);

        /* List to XML and reverse */
        String listToString = objectToString(list);
        List parsedList = (List) stringToObject(listToString);
        System.out.println("List to XML: \n" + listToString + "\nXML to list:\n" + parsedList);
    }

    public static String objectToString(Object hashMap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XMLEncoder xmlEncoder = new XMLEncoder(bos);
        xmlEncoder.writeObject(hashMap);
        xmlEncoder.close();
        return bos.toString();
    }

    public static Object stringToObject(String string) {
        XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream(string.getBytes()));
        return xmlDecoder.readObject();
    }
}

Output

Map to XML: 
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_45" class="java.beans.XMLDecoder">
 <object class="java.util.HashMap">
  <void method="put">
   <string>lastName</string>
   <string>Kumar</string>
  </void>
  <void method="put">
   <string>contents</string>
   <object class="java.util.ArrayList">
    <void method="add">
     <int>20</int>
    </void>
    <void method="add">
     <int>30</int>
    </void>
    <void method="add">
     <int>40</int>
    </void>
    <void method="add">
     <object class="java.util.HashMap" id="HashMap0">
      <void method="put">
       <string>timeOut</string>
       <string>5:00</string>
      </void>
      <void method="put">
       <string>timeIn</string>
       <string>8:00</string>
      </void>
     </object>
    </void>
   </object>
  </void>
  <void method="put">
   <string>timing</string>
   <object idref="HashMap0"/>
  </void>
  <void method="put">
   <string>firstName</string>
   <string>Pritom</string>
  </void>
 </object>
</java>

XML to map:
{
    lastName=Kumar, 
    contents=[
        20, 
        30, 
        40, 
        {
            timeOut=5:00, 
            timeIn=8:00
        }
    ], 
    firstName=Pritom, 
    timing={
        timeOut=5:00, 
        timeIn=8:00
    }
}



List to XML: 
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_45" class="java.beans.XMLDecoder">
 <object class="java.util.ArrayList">
  <void method="add">
   <int>20</int>
  </void>
  <void method="add">
   <int>30</int>
  </void>
  <void method="add">
   <int>40</int>
  </void>
  <void method="add">
   <object class="java.util.HashMap">
    <void method="put">
     <string>timeOut</string>
     <string>5:00</string>
    </void>
    <void method="put">
     <string>timeIn</string>
     <string>8:00</string>
    </void>
   </object>
  </void>
 </object>
</java>

XML to list:
[20, 30, 40, {timeOut=5:00, timeIn=8:00}]