欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Hibernate通用数据库操作代码

程序员文章站 2024-02-20 12:50:34
insert方法 复制代码 代码如下:public void insert(object o){session session = hibernatesessionfact...
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;}