Hibernate作为一个ORM框架,并不一定使用在Web应用中,可以使用在任何类型应用的数据库持久层进行编程。
本文将展示Hibernate和Struts2结合使用,完成Web应用的实例。
接口CustomerDAO定义了数据访问逻辑
package dao;
import java.util.List;
import vo.Customer;
public interface CustomerDAO {
public List<Customer> selectAll();
public Customer selectByName(String custname);
public Customer selectByNamePwd(String custname,String pwd);
public void insert(Customer cust);
}
接口CustomerDAO实现类CustomerDAOHibImpl.java
package dao.Impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateSessionFactory;
import vo.Customer;
import dao.CustomerDAO;
public class CustomerDAOHibImpl implements CustomerDAO{
@Override
public List<Customer> selectAll() {
Session session = HibernateSessionFactory.getSession();
String hql="from Customer";
List<Customer> list = session.createQuery(hql).list();
return list;
}
@Override
public Customer selectByName(String custname) {
Customer cust=null;
Session session = HibernateSessionFactory.getSession();
String hql="from Customer where custname='"+custname+"'";
List<Customer> list = session.createQuery(hql).list();
if(list.size()>0){
cust=list.get(0);
}
return cust;
}
@Override
public Customer selectByNamePwd(String custname, String pwd) {
Session session = HibernateSessionFactory.getSession();
Customer cust=null;
String hql = "from Customer where custname=? and pwd=?";
Query query = session.createQuery(hql);
query.setString(0, custname);
query.setString(1, pwd);
List <Customer> list = query.list();
if(list.size()>0){
cust=list.get(0);
}
return cust;
}
@Override
public void insert(Customer cust) {
Session session = HibernateSessionFactory.getSession();
Transaction tran = session.beginTransaction();
session.save(cust);
tran.commit();
}
}
至此,已经使用Hibernate框架实现了数据访问层。
与以前使用JDBC的CustomerDAOImpl类比较,可见使用Hibernate比起JDBC更为简练,
如果数据表结构复杂,将更能体现Hibernate在关联映射方面的优势。