编写hibernateDao,使dao层都实现hibernateDao
2024-08-28 15:30:56
package com.wiseweb.core.dao; import java.io.Serializable;
import java.util.ArrayList;
import java.util.List; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired; @SuppressWarnings("unchecked")
public abstract class HibernateDAO <T, P extends Serializable> { @Autowired
private SessionFactory sessionFactory; /**
* 获取sessionFactory工厂
* @return
*/
protected SessionFactory getSessionFactory(){ return this.sessionFactory;
} /**
* 获取数据库session会话
* @return
*/
protected Session getSession(){ return this.sessionFactory != null ? this.sessionFactory.getCurrentSession() : null;
}
/**
* 保存数据库
* @param object
* @throws Exception
*/
public void save(T object) throws Exception{ if (getSession() != null) {
getSession().save(object);
}
}
/**
* 删除数据库
* @param object
* @throws Exception
*/
public void delete(T object) throws Exception{ if (getSession() != null) {
getSession().delete(object);
}
}
/**
* 更新数据库
* @param object
* @throws Exception
*/
public void update(T object) throws Exception{ if (getSession() != null) {
getSession().update(object);
}
}
/**
* 根据id查询
* @param tClass
* @param id
* @return
* @throws Exception
*/
public T get(Class<T> tClass, P id) throws Exception{ if (getSession() != null) {
return (T) getSession().get(tClass, id);
}
return null;
}
/**
* 根据sql语句做相应的查询
* @param hql
* @return
* @throws Exception
*/
public List<T> createQueryByHql(String hql) throws Exception{ List<T> list = new ArrayList<T>();
if (hql != null || !hql.equals("")) {
if (getSession() != null) {
list = getSession().createQuery(hql).list();
}
}
return list;
}
/**
* 分页查询
* @param hql
* @param pageNum
* @param pageSize
* @return
* @throws Exception
*/
public List<T> createQueryByHql(String hql, int pageNum, int pageSize) throws Exception{ List<T> list = new ArrayList<T>();
if (hql != null || !hql.equals("")) {
if (getSession() != null) {
Query query = getSession().createQuery(hql);
query.setFirstResult((pageNum - 1) * pageSize);
query.setMaxResults(pageSize);
list = query.list();
}
}
return list;
}
}
最新文章
- ABAP游标的使用
- jQuery Flat Shadow – 轻松实现漂亮的长阴影效果
- MWeb
- DUILIB CDialogBuilder 使用问题
- 【IHttpHandler】IHttpModule实现URL重写
- openwrt的交叉编译
- 广播接收者 BroadcastReceiver 示例-1
- 06_Elasticsearch 批量获取mget
- 如何利用【百度地图API】,制作房产酒店地图?(下)——结合自己的数据库
- Python - 字母算术谜题
- android网络编程之HttpUrlConnection的讲解--POST请求
- js-基本语法
- Java生成带logo二维码
- oracle 如何将一个字段内容拆分多行显示
- Ural 2036. Intersect Until You&#39;re Sick of It 计算几何
- 蚂蚁男孩.队列组件(Framework.Mayiboy.Queue)
- hdu4965矩阵快速幂
- Docs命令大全 备用
- Android——Activity和Intent及Activity的生命周期
- class path resource [logback.xml] cannot be resolved to URL because it does not exist 问题解决