首页 > 代码库 > hibernateDaoSupport中的一些公用常用方法
hibernateDaoSupport中的一些公用常用方法
/**
* 删除记录
* @param entity BO的对象
* <pre>
* this.getHibernateTemplate().delete(entity);
* 按照规范,调用ECLRecordDelete记录删除的BO信息;
* </pre>
*/
public void delete(Object entity){
this.getHibernateTemplate().delete(entity);
}
/**
* 通过id获得记录
* @param Class entityClass,对象类型
* @param Serializable id,BO的id值
* <pre>
* return hibernateTemplate.get(entityClass,id);
* </pre>
*/
public Object findById(Class entityClass, Serializable id) {
return this.getHibernateTemplate().get(entityClass,id);
}
/**
* 获得延迟加载数据
* @param Object object,需要加载的对象
* <pre>
* Hibernate.initialize(object);
* </pre>
*/
public void getLazyData(Object object) {
this.getHibernateTemplate().initialize(object);
}
/**
* 增加记录
* @param Object entity,需要保存的BO
* <pre>
* hibernateTemplate.save(entity);
* return entity;
* </pre>
*/
public Object save(Object entity) {
Object id = (Object)this.getHibernateTemplate().save(entity);
return id;
}
/**
* 修改记录
* @param Object,要修改的BO
* <pre>
* hibernateTemplate.update(entity);
* </pre>
*/
public void update(Object entity) {
this.getHibernateTemplate().update(entity);
}
//通过传递多个条件查询表记录
public List findByHQLCondition(Class entityClass,List propertyNameList,List propertyValueList){
StringBuffer sqlStr = new StringBuffer();
sqlStr.append("from ").append(entityClass.getName()).append(" as bo");
sqlStr.append(" where 1=1 ");
if(propertyNameList !=null && propertyValueList!=null && propertyNameList.size() == propertyValueList.size()){
for(int i=0;i<propertyNameList.size();i++){
sqlStr.append(" and bo.").append(propertyNameList.get(i)).append(" = :").append(propertyNameList.get(i));
}
}else{
return null;
}
final String sql = sqlStr.toString();
final List propertyNList = propertyNameList;
final List propertyVList = propertyValueList;
return(List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
List li = new ArrayList();
Query query = session.createQuery(sql);
for(int i=0;i<propertyNList.size();i++){
query.setParameter(propertyNList.get(i).toString(),propertyVList.get(i));
}
Iterator it = query.iterate();
while(it.hasNext()){
li.add(it.next());
}
return li;
}
});
}
//根据传递的HQL语句,来查询数据库
public List findByHQL(String hql){
return this.getHibernateTemplate().find(hql);
}
//只根据一个条件来查询数据库字段
public List findByOneHQLCondition(Class entityClass,String propertyName,String propertyValue) {
StringBuffer sqlStr = new StringBuffer();
sqlStr.append("from ").append(entityClass.getName()).append(" as bo where bo.");
sqlStr.append(propertyName);
sqlStr.append(" = :");
sqlStr.append(propertyName);
final String sql = sqlStr.toString();
return getHibernateTemplate().findByNamedParam(sql, propertyName,propertyValue);
hibernateDaoSupport中的一些公用常用方法