其实对Hibernate进行分析后可以发现,这个Hibernate对于对象的增加。删除,更新是差不多的,所以可以把他们整
合到一个工具类中去。还有就是,因为查询是很复杂的,所以对于数据库的查询,就有相对应的接口,类似于JDBC中
的PreparedStatemented这个类。下面我们先看一下工具类的增强
package com.bird.hibernate.test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
@SuppressWarnings("deprecation")
public final class Hibernateutils {
private static SessionFactory sf;
private Hibernateutils(){}
static{
Configuration cfg = new Configuration();
cfg.configure();
sf = cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sf;
}
public static Session getSession(){
return sf.openSession();
}
public static void add(Object entity){
Session s = null;
Transaction ts = null;
try {
s = sf.openSession();
ts = s.beginTransaction();
s.save(entity);
ts.commit();
} catch (HibernateException e) {
if (ts != null)
ts.rollback();
throw e;
} finally {
if (s != null)
s.close();
}
}
public static void update(Object entity){
Session s = null;
Transaction ts = null;
try {
s = sf.openSession();
ts = s.beginTransaction();
s.update(entity);
ts.commit();
} catch (HibernateException e) {
if (ts != null)
ts.rollback();
throw e;
} finally {
if (s != null)
s.close();
}
}
public static void delete(Object entity){
Session s = null;
Transaction ts = null;
try {
s = sf.openSession();
ts = s.beginTransaction();
s.delete(entity);
ts.commit();
} catch (HibernateException e) {
if (ts != null)
ts.rollback();
throw e;
} finally {
if (s != null)
s.close();
}
}
}
然后是查询,使用hql是只面向对象的,不考虑什么表的问题。其他的和jdbc类是
package com.bird.hibernate.test;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.bird.domain.User;
public class QueryTest {
/**
* @param args
*/
public static void main(String[] args) {
query("bird");
}
public static void query(String name){
Session s = null;
try {
s = Hibernateutils.getSession();
String hql="from User as use where use.name=?";
Query query = s.createQuery(hql);
query.setString(0, name);
@SuppressWarnings("unchecked")
List<Object> list = query.list();
for(Object o: list){
System.out.println(((User)o).getName());
}
} catch (HibernateException e) {
throw e;
} finally {
if (s != null)
s.close();
}
}
}