科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道Hibernate编写通用数据库操作代码演示

Hibernate编写通用数据库操作代码演示

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

Hibernate编写通用数据库操作代码演示

作者:baocl 来源:赛迪网技术社区 2007年11月1日

关键字: 代码 数据库 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             ht.put(rsmd.getColumnName(i+1),rs.getObject(i+1));
        }
        array.add(ht);
    }
    HibernateSessionFactory.clossSession();
    return array;
}查看本文来源
    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章