Thursday, February 23, 2012

Hibernate - HQL with Parameters

Let us now parametrize our HQL query, so we can get Users by their firstName.

Update your UserDAO, like this:
 package org.confucius;   

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class UserDAO {

// HQL with parameters
public static List<User> getUsers (String firstName) throws Exception{
List<User> users = new ArrayList<User>();
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
Query query = session.createQuery("from User where firstName = :firstName");
query.setParameter("firstName", firstName);
users = (List<User>) query.list();
tx.commit();
}
catch (Exception e){
tx.rollback();
throw e;
}

session.close();
return users;
}

// HQL with no parameters
public static List<User> getUsers () throws Exception{
List<User> users = new ArrayList<User>();
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
Query query = session.createQuery("from User");
users = (List<User>) query.list();
tx.commit();
}
catch (Exception e){
tx.rollback();
throw e;
}

session.close();
return users;
}


// Getting an object given its Id
public static User getUser (long userId) throws Exception{
User user = null;
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
user = (User) session.get(User.class, userId);
tx.commit();
}
catch (Exception e){
tx.rollback();
throw e;
}

session.close();
return user;
}


// Persist
public static void persist (User user) throws Exception{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
session.persist(user);
tx.commit();

} catch (Exception e){
tx.rollback();
throw e;
}

session.close();
}
}

Update your TstPersistence.java to use this new DAO method, like this:
 package org.confucius;   

import java.util.Iterator;
import java.util.List;


public class TestPersistence {

public static void main(String[] args) {
try {
List<User> users = UserDAO.getUsers("Joe");
for (Iterator<User> iter = users.iterator(); iter.hasNext();)
System.out.println(iter.next());

} catch (Exception e) {
e.printStackTrace();
}
}
}

R-click on the TestPersistence.java file in your Eclipse Navigator view.
Select Run As->Java Application

You will see Joe Trumpet and details about his Cart printed to the console.

No comments: