使用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; }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值