这两天都在研究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();
}
完毕~~