Hibernate通用数据库操作代码
insert方法
public void insert(Object o){
Session session = HibernateSessionFactory.currentSession();
Transaction t = session.beginTransaction();
session.save(o);
t.commit();
HibernateSessionFactory.clossSession();
}
delete方法
public void delete(Object o,Serializable id){
Session session = HibernateSessionFactory.currentSession():
Transaction t = session.beginTransaction();
Object o = session.get(o.class,id);
if(o!=null){
session.delete(o);
}
t.commit();
HibernateSessionFactory.clossSession();
}
update方法
public void update(Object o,Serializable id){
Session session = HibernateSessionFactory.currentSession();
Transaction t = session.beginTransaction();
session.update(o,id);
t.commit();
HibernateSessionFactory.clossSession();
}
基于HQL的通用select方法
public ArrayList select(String sql){
Session session = HibernateSessionFactory.currentSession();
Query query = createQuery(sql);
List list = query.list();
HibernateSessionFactory.clossSession();
return (ArrayList)list;
}
基于SQL的通用select方法
public ArrayList select(String sql) throws Exception{
Session session = HibernateSessionFactory.currentSession();
Connection con = session.connection();
PreparedStatement pstmt = con.preparedStatement(sql);
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
Hashtable ht = null;
ArrayList array = new ArrayList();
while(rs.next()){
ht = new Hashtable();
for(int i=0;i< rsmd.getColumnCount();i++){
ht.put(rsmd.getColumnName(i+1),rs.getObject(i+1));
}
array.add(ht);
}
HibernateSessionFactory.clossSession();
return array;
}
附一个流行的:
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateSessionFactory{
public static final SessionFactory sessionFactory;
static{
try{
//采用默认的hibernate.cfg.xml来启动一个Configuration的实例
Configuration configuration=new Configuration().configure();
//由Configuration的实例来创建一个SessionFactory实例
sessionFactory = configuration.buildSessionFactory();
}catch (Throwable ex){
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
//ThreadLocal并不是线程本地化的实现,而是线程局部变量。也就是说每个使用该变量的线程都必须为
//该变量提供一个副本,每个线程改变该变量的值仅仅是改变该副本的值,而不会影响其他线程的该变量
//的值.
//ThreadLocal是隔离多个线程的数据共享,不存在多个线程之间共享资源,因此不再需要对线程同步
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException{
Session s = (Session) session.get();
//如果该线程还没有Session,则创建一个新的Session
if (s == null){
s = sessionFactory.openSession();
//将获得的Session变量存储在ThreadLocal变量session里
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}