Hibernate插入和读取数据实例【原创】

这两天都在研究Hibernate,大师们说有多好用我就看有多好用,不想说太多,以下是插入和读取的两个实例片段:

动作类(业务类):

Public Class ServiceAncestor{  

public List query(String hql) throws Exception {//用于查询
   ArrayList list = new ArrayList(0);
   try {
    session = factory.openSession();
    query = session.createQuery(hql);
    list = (ArrayList)query.list();
   } catch (Exception e) {
    logger.error(e);
    throw e;
   } finally {
    list.trimToSize();
    closeSession();
   }
   return list;
}

 

public void insert(Object tableBean) throws Exception {//用于插入

   try {
    session = factory.openSession();
    tx = session.beginTransaction();
    //
    session.clear();
    session.save(tableBean);
    session.flush();
    //
    tx.commit();
   } catch (Exception e) {
    System.out.println("Hibernate插入的时候错啦::!!!"+e);
    e.printStackTrace();
    logger.error(e);
    tx.rollback();
    throw e;
   } finally {
    closeSession();
   }
}

}

读取并显示数据的jsp片段:

   <%     
     try {
          ServiceAncestor sa = new ServiceAncestor();
          String hql = "select contribute.IName,contribute.IAmount,contribute.ILovemess from Contribute contribute";
          List list = sa.query(hql);
          for(int i = 0;i<list.size();i++){
          Object[] obj=(Object[])list.get(i);           
            System.out.println(obj[0]);

           }
         
         
     }catch (HibernateException err) {
     
      System.out.println("Hinernate查询父亲出错了啦!"+err);
      err.printStackTrace();
     }

%>

插入数据jsp片段:


    try {
          ServiceAncestor sa = new ServiceAncestor();
    
     Contribute contribute = new Contribute();
    
     contribute.setStan("8");
     System.out.println("Stan::"+contribute.getStan());
     contribute.setIName(ctbName);
     System.out.println("Name::"+contribute.getIName());
     contribute.setCreatedt(new java.util.Date());
     System.out.println("Createdt::"+contribute.getCreatedt());
     contribute.setIAddres(ctbAdder);    
     System.out.println("address|:;"+contribute.getIAddres());      
     contribute.setIAmount(ctbMoney);
     System.out.println("money::"+contribute.getIAmount());
     contribute.setTel(ctbNumber);
     System.out.println("number::"+contribute.getTel());
     contribute.setILovemess(comment);
     System.out.println("comment::"+contribute.getILovemess());   
    
     sa.insert(contribute);
    

    } catch (HibernateException err) {
    
     System.out.println("Hinernate出错了!"+err);
     err.printStackTrace();
    }

 

完毕~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值