整理自网络
//事务中,持久态的对象,在内存中修改之后,会悄木声声的修改DB
Session session = HibernateSessionFactory.getSession();
TAircorp a =(TAircorp)session.get("test.hibernate.persistent.TAircorp", 28L);
session.beginTransaction();
a.setCAircorpeng(a.getCAircorpeng()+"3");//此处内存中修改,并没有显示的更新DB
session.getTransaction().commit();//事务提交之后,会修改DB
HibernateSessionFactory.closeSession();
Hibernate: select …
Hibernate: update …
缓存机制
1 save update saveOrUpdate marge 在flush之后才会更新DB
2 查询缓存
查询
Public List<ApOperInfo> findByExample(AoOperInfo ap){
Criterion customized = Restrictions.sqlRestriction(
" valid=1 and service_category_id = 77
and to_char(expire_date,'yyyyMMdd')>to_char(sysdate,'yyyyMMdd') ");
//扩展规则可以直接写sql.单表的话,不用写别名,直接写字段就可以.
Criteria criteria = getSession().createCriteria(ap.getClass());
Example example = Example.create(ap);
example.enableLike();
criteria.add(example);
criteria.add(customized);
criteria.setFirstResult(firstResult);
criteria.setMaxResults(p.getCountEachPage());
criteria.addOrder(Order.asc(p.getOrderBy()));
criteria.list();
return list;
}
Public List<ApOperInfo> findByExample(ApOperInfo ap){
Criteria criteria = dao.getSession().createCriteria(ApOperInfo.class);
if(ap != null){
Example example = Example.create(ap);
example.enableLike();
criteria.add(example);
}
// 过滤所有和当前业务互斥的业务
StringBuffer whereHql = new StringBuffer();
whereHql.append(
"(
{alias}.entity_id not in (
select se.entity_id from ap_oper_info_exclusion se where se.ex_entity_Id=? )" +
" and
{alias}.entity_id not in (
select se.ex_entity_Id from ap_oper_info_exclusion se where se.entity_id=?)
)"
);
whereHql.append(" and {alias}.entity_id != ? ");
criteria.add(Restrictions.sqlRestriction(whereHql.toString()
, new Object[]{id, id, id}
, new Type[]{Hibernate.LONG,Hibernate.LONG,Hibernate.LONG}));
return criteria.list();
}
//扩展规则甚至可以写SQL子查询.{alias}.就是别名.