SQL queries have slight differences between different databases.
Hibernate has a SQL version called HQL - which closely mimics the SQL that you are used to. Behind the scenes Hibernate generates the correct SQL queries based on the database.
Let us update UserDAO to use HQL to get a list of Users from the database.
Your UserDAO.java will now look 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 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();
}
}
The HQL query "form User" is, in principle, equivalent to the SQL query "select from user". But Hibernate will generate all the SQL queries needed to get the Users, their Carts and the Items in the cart.
So HQL queries pack a lot of punch. In addition, they are optimized for the Database they are working against.
Update your TestPersistence.java to use this new HQL based DAO method:
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();
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 the user Joe printed to the console, including his cart and its items.
Note the SQL queries that Hibernate generated : the HQL "from User" query resulted in multiple SQL queries.
No comments:
Post a Comment