首页>代码>springMVC3.2+Hibernate4+freemarker入门简单小例子,适合初学者>/springMVC_Hibernate_freemarker/src/com/xxx/core/dao/base/BaseDao.java
package com.xxx.core.dao.base; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; /** * DAO基类 定义数据操作的常用方法 * * @author sxhjhf * */ public abstract class BaseDao<T> { @Resource private SessionFactory sessionFactory; /** * 获取针对的实体类 * * @return 针对的实体类 */ abstract protected Class<T> getEntity(); /** * 获取session链接 * * @return 数据库session链接 */ public Session getSession() { return sessionFactory.getCurrentSession(); } /** * 根据条件查询 * * @param hql语句 * @param values参数 * @return 查询结果 */ public Query createQuery(String hql, Object... values) { Query q = null; q = getSession().createQuery(hql); for (int i = 0; i < values.length; i++) { q.setParameter(i, values[i]); } return q; } /** * 简单分页获取数据 * * @param page查询页码 * @return 查询结果列表,查询失败或者无数据返回null */ public List getPageList(int page) { List list = null; if (page < 1) { return null; } int all = Integer.parseInt(getSession() .createQuery("select count(*) from " + getEntity()) .uniqueResult().toString()); int starPage = (page - 1) * 10; if (starPage + 1 > all) { return null; } int endPage = page * 10 > all ? all : (page * 10 - 1); list = getSession().createQuery("from " + getEntity() + " where 1=1") .list().subList(starPage, endPage); return list; } /** * 添加 * * @param obj * @return */ public Serializable save(Object obj) { return getSession().save(obj); } /** * 删除 * * @param id */ public void remove(int id) { getSession().createQuery("delete " + getEntity() + " where id=" + id) .executeUpdate(); } /** * 更新 * * @param obj */ public void change(Object obj) { getSession().update(obj); } /** * 通过id查询 * * @param id * @return */ public Object getById(int id) { return getSession().createQuery( "from " + getEntity() + "where id=" + id).uniqueResult(); } /** * 直接查询所有实体数据 * * @return */ public List<T> getAllList() { return getSession().createQuery("from " + getEntity() + " where 1=1") .list(); } }

G0GO LV1
2021年4月14日
583062742 LV1
2020年9月5日
1121323395 LV1
2019年11月29日
z924931408 LV25
2019年3月13日
源灵主 LV1
2018年11月15日
zhouzhihong LV2
2018年10月18日
yahuszu LV1
2018年8月30日
zimi1054367550 LV1
2018年7月25日
13982641004 LV1
2018年6月29日
yaob1985 LV8
2018年6月18日