Tuesday, 10 January 2017

Hibernate named query examples


Scattered HQL string literals in Java code are hard to maintain and look ugly. To avoid it, Hibernate come out a technique called “names queries”, it lets developer to put all HQL into the XML mapping file or via annotation.

XML mapping file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
      <class name="com.dto.EmployeeDTO"  table="EMPLOYEES">
            <id name="id" column="ID"><generator class="assigned"/></id>
            <property name="empId" column="EMP_ID" />
            <property name="empFirstName" column="EMP_FIRST_NAME" />
            <property name="empLastName" column="EMP_LAST_NAME" />
            <property name="createdOn" column="CREATED_ON"/>
      </class>

      <!-- Native SQL in named query -->
      <sql-query name="updateEmployee">
            <![CDATA[
                  UPDATE EMPLOYEES SET EMP_LAST_NAME=:empLastName WHERE EMP_ID=:employeeId
            ]]>
      </sql-query>

      <!-- HQL in named query -->
      <query name="findEmpById">
        <![CDATA[from EmployeeDTO e where e.empId = :employeeId]]>
    </query>
</hibernate-mapping>

HQL and Native SQL in annotation
<!-- HQL in named query -->
@NamedQueries({
     @NamedQuery(
                name = "updateEmployee",
                query = "from EmployeeDTO e where e.empId = :employeeId"
     )
})

<!-- Native SQL in named query -->
@NamedNativeQueries({
     @NamedNativeQuery(
                name = "updateEmployee",
                query = "UPDATE EMPLOYEES SET EMP_LAST_NAME=:empLastName WHERE EMP_ID=:employeeId",
                resultClass = EmployeeDTO.class
     )
})
@Entity
@Table(name = "EMPLOYEES")
public class EmployeeDTO implements java.io.Serializable {
     ...
}

Java Code to use the named Query:
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibernateNamedQuery extends HibernateDaoSupport {

      public int updateEmployee(String p_employeeId, String p_modifiedBy) {
            Session session = null;
            try {
                  session = getHibernateTemplate().getSessionFactory().openSession();
                  Query query = session.getNamedQuery("updateEmployee");
                 
                  query = query.setString("empLastName", "Kumar");
                 
                  int rowsUpdated = query.executeUpdate();
     
                  return rowsUpdated;
            } finally {
                  releaseSession(session);
            }
      }
     
      public List<Object[]> fetchEmployeeDetails(String empId) {
            Session session = null;
            try {
                  session = getHibernateTemplate().getSessionFactory().openSession();
                 
                  Query query = session.getNamedQuery("findEmpById");
                  query = query.setString("employeeId",empId);
                 
                  return query.list();
            } finally {
                  releaseSession(session);
            }
      }
}


Check two trees are identical or not

Problem:
Given two binary trees, write a function to check if they are equal or not.

Solution:
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

Algorithm:
isTreesIdenticalRec(Node root1, Node root2) :
1. Termination Condition: If both trees are empty then return true.
2. else if both trees are non-empty
     (a) Check data of the root nodes (root1->data ==  root2->data)
     (b) Check left subtrees recursively
                   call isTreesIdenticalRec(root1->left, root2->left)
     (c) Check right subtrees recursively
                   call isTreesIdenticalRec(root1->right, root2->right)
     (d) If a,b and c are true then return true.
3. else return false(=one is empty and another is not).

package crack.coding.interview;
/**
 * Class to check whether two binary trees are identical.
 * @author rajesh.dixit
 */
classIdenBinaryTree {
    
     /**
      * @author rajesh.dixit
      * Node of the Tree.
      */
     private static classNode {
           int data;
           Node left, right;

           Node(int item) {
                data = item;
                left = right = null;
           }
     }
    
     Node root1, root2;
    
     /**
      * To check whether Trees are Identical or not.
      * @param root1
      * @param root2
      * @return true/false
      */
     private static boolean isTreesIdenticalRec(Node root1, Node root2) {
          
           if(root1==null&& root2==null) {
                return true;
           } else if(root1!=null&& root2!=null) {
                return(root1.data == root2.data
                           && isTreesIdenticalRec(root1.left, root2.left)
                           && isTreesIdenticalRec(root1.right, root2.right));
           } else {
                return false;
           }
     }

     /**
      * Main method: Program start point.
      * @param args
      */
     public static void main(String[] args) {
          
           IdenBinaryTree tree1 = new IdenBinaryTree();
           tree1.root1 = new Node(1);
           tree1.root1.left = new Node(2);
           tree1.root1.right = new Node(3);
           tree1.root1.left.left = new Node(4);
           tree1.root1.left.right = new Node(5);

           IdenBinaryTree tree2 = new IdenBinaryTree();
           tree2.root2 = new Node(1);
           tree2.root2.left = new Node(2);
           tree2.root2.right = new Node(3);
           tree2.root2.left.left = new Node(4);
           tree2.root2.left.right = new Node(5);

           if (isTreesIdenticalRec(tree1.root1, tree2.root2)) {
                System.out.println("Trees are identical");
           } else {
                System.out.println("Trees are not identical");
           }
     }
}
Related Posts Plugin for WordPress, Blogger...