当前位置: 代码迷 >> 综合 >> Java Jsp+Mybatis+Servlet+Mysql实现记账管理系统(普通用户/管理员 财务统计/财务管理/系统管理)
  详细解决方案

Java Jsp+Mybatis+Servlet+Mysql实现记账管理系统(普通用户/管理员 财务统计/财务管理/系统管理)

热度:81   发布时间:2024-03-05 21:01:30.0

博客目录

  • 记账管理系统
    • 功能截图
    • 功能点以及流程图
    • 技术点介绍
    • 源码(关键部分)
    • 写在最后

记账管理系统

本记账系统是一个基于国内外电子商务网站的发展现状,采用B2C(Business to Consumers)模式开发的电子商务平台,它的价值所在对于那些随意消费性的人群能起到一个很大的警示作用,而且系统扩张性很强,能根据客户的不同需求进行快速改进。

功能截图

用户注册:
在这里插入图片描述
管理员用户信息:
在这里插入图片描述
首页:
在这里插入图片描述
用户财务记录信息:
在这里插入图片描述
财务月统计:
在这里插入图片描述
财务年收入:
在这里插入图片描述

功能点以及流程图

本系统为用户提供了以下功能:
信息管理(个人信息修改、系统版权信息);
财务管理(财务信息、财务记录);
财务统计(月收支查询、年收支查询);
系统管理(用户信息管理、管理员信息管理);

1、用例图:
在这里插入图片描述
在这里插入图片描述
2、系统流程图:
在这里插入图片描述

技术点介绍

该系统的实现要求使用B/S架构和MVC模式,使用JSP进行前台页面实现,后台数据库的实现使用Mysql。
软件环境 :
操作系统——windows 7
数据库——Mysql
应用中间件——Tomcat7.0
编辑环境——Eclipse

源码(关键部分)

1、记账管理的Dao:ZhangDaoImpl.java

package com.biyeseng.dao;	import java.util.ArrayList;	
import java.util.List;	import org.apache.commons.lang.StringUtils;	import com.biyeseng.common.HibernateGenericDao;	
import com.biyeseng.common.PageBean;	
import com.biyeseng.vo.Zhang;	/*** * @author biyeseng* @company www.biyeseng.cn**/
public class ZhangDAOImpl extends HibernateGenericDao<Zhang> implements	ZhangDAO {
    	public void save(Zhang zhang) {
    	super.save(zhang);	}	public void update(Zhang zhang) {
    	super.update(zhang);	}	public void delete(Zhang zhang) {
    	super.remove(zhang);	}	public Zhang getZhang(Zhang zhang) {
    	return get(zhang.getId());	}	public Zhang getZhang(Long id) {
    	return get(id);	}	public List<Zhang> getAllZhang() {
    	return getAll();	}	public List<Zhang> findPageInfoZhang(Zhang zhang, PageBean pageBean) {
    	List args = new ArrayList();	StringBuffer sql = new StringBuffer();	sql.append(" SELECT * FROM zhang WHERE 1=1 ");	sql = getStringBuffer(zhang, sql, args);	return getPageInfo(pageBean, sql.toString(), args);	}	public List<Zhang> findPageInfoZhang1(Zhang zhang, PageBean pageBean) {
    	List args = new ArrayList();	StringBuffer sql = new StringBuffer();	sql.append(" SELECT * FROM zhang WHERE NAME<>'admin' ");	sql = getStringBuffer(zhang, sql, args);	return getPageInfo(pageBean, sql.toString(), args);	}	public Integer getCount1(Zhang zhang) {
    	List args = new ArrayList();	StringBuffer sql = new StringBuffer();	sql.append(" SELECT COUNT(0) FROM zhang WHERE NAME<>'admin' ");	sql = getStringBuffer(zhang, sql, args);	return super.getCount(sql.toString(), args.toArray());	}	public Integer getCount(Zhang zhang) {
    	List args = new ArrayList();	StringBuffer sql = new StringBuffer();	sql.append(" SELECT COUNT(0) FROM zhang WHERE 1=1 ");	sql = getStringBuffer(zhang, sql, args);	return super.getCount(sql.toString(), args.toArray());	}	/** * 构造查询条件 * * @param zhang * @param buf3 * @param args * @return * @author Alex 10/28/2011 create */	private StringBuffer getStringBuffer(Zhang zhang, StringBuffer buf,	List args) {
    	/* * 需要加入查询条件时封装 */	if (StringUtils.isNotBlank(zhang.getName())) {
    	buf.append(" and name like '%"+zhang.getName().trim()+"%' ");	}	if (StringUtils.isNotBlank(zhang.getType())) {
    	buf.append(" and type = ? ");	args.add(zhang.getType().trim());	}if (StringUtils.isNotBlank(zhang.getKind())) {
    	buf.append(" and kind = ? ");	args.add(zhang.getKind().trim());	}	return buf;	}	
}	

管理员Dao:AdminDaoImpl.java

package com.biyeseng.dao;	import java.util.ArrayList;	
import java.util.List;	import org.apache.commons.lang.StringUtils;	import com.biyeseng.common.HibernateGenericDao;	
import com.biyeseng.common.PageBean;	
import com.biyeseng.vo.Admin;	/*** * @author biyeseng* @company www.biyeseng.cn**/
public class AdminDAOImpl extends HibernateGenericDao<Admin> implements	AdminDAO {
    	public void save(Admin admin) {
    	super.save(admin);	}	public void update(Admin admin) {
    	super.update(admin);	}	public void delete(Admin admin) {
    	super.remove(admin);	}	public Admin getAdmin(Admin admin) {
    	return get(admin.getId());	}	public Admin getAdmin(Long id) {
    	return get(id);	}	public List<Admin> getAllAdmin() {
    	return getAll();	}	public List<Admin> findPageInfoAdmin(Admin admin, PageBean pageBean) {
    	List args = new ArrayList();	StringBuffer sql = new StringBuffer();	sql.append(" SELECT * FROM admin WHERE 1=1 ");	sql = getStringBuffer(admin, sql, args);	return getPageInfo(pageBean, sql.toString(), args);	}	public List<Admin> findPageInfoAdmin1(Admin admin, PageBean pageBean) {
    	List args = new ArrayList();	StringBuffer sql = new StringBuffer();	sql.append(" SELECT * FROM admin WHERE NAME<>'admin' ");	sql = getStringBuffer(admin, sql, args);	return getPageInfo(pageBean, sql.toString(), args);	}	public Integer getCount1(Admin admin) {
    	List args = new ArrayList();	StringBuffer sql = new StringBuffer();	sql.append(" SELECT COUNT(0) FROM admin WHERE NAME<>'admin' ");	sql = getStringBuffer(admin, sql, args);	return super.getCount(sql.toString(), args.toArray());	}	public Integer getCount(Admin admin) {
    	List args = new ArrayList();	StringBuffer sql = new StringBuffer();	sql.append(" SELECT COUNT(0) FROM admin WHERE 1=1 ");	sql = getStringBuffer(admin, sql, args);	return super.getCount(sql.toString(), args.toArray());	}	/** * 构造查询条件 * * @param admin * @param buf3 * @param args * @return * @author Alex 10/28/2011 create */	private StringBuffer getStringBuffer(Admin admin, StringBuffer buf,	List args) {
    	/* * 需要加入查询条件时封装 */	if (StringUtils.isNotBlank(admin.getName())) {
    	buf.append(" and name = ? ");	args.add(admin.getName().trim());	}	if (StringUtils.isNotBlank(admin.getPass())) {
    	buf.append(" and pass = ? ");	args.add(admin.getPass().trim());	}	return buf;	}	
}	

2、业务逻辑类:
ZhanghaoService.java

package com.biyeseng.service;	import java.util.List;	import com.biyeseng.common.PageBean;	
import com.biyeseng.dao.ZhangDAO;	
import com.biyeseng.vo.Zhang;	/*** * @author biyeseng* @company www.biyeseng.cn**/
public class ZhangServiceImpl implements ZhangService {
    	private ZhangDAO zhangDAO;	public void save(Zhang zhang) {
    	zhangDAO.save(zhang);	}	public void update(Zhang zhang) {
    	zhangDAO.update(zhang);	}	public Zhang getZhang(Zhang zhang) {
    	return zhangDAO.getZhang(zhang);	}	public Zhang getZhang(Long id) {
    	return zhangDAO.getZhang(id);	}	public void delete(Zhang zhang) {
    	zhangDAO.delete(zhang);	}	public List<Zhang> findPageInfoZhang(Zhang zhang, PageBean pageBean) {
    	return zhangDAO.findPageInfoZhang(zhang, pageBean);	}	public Integer getCount(Zhang zhang) {
    	return zhangDAO.getCount(zhang);	}	public void setZhangDAO(ZhangDAO zhangDAO) {
    	this.zhangDAO = zhangDAO;	}	public List<Zhang> findPageInfoZhang1(Zhang zhang, PageBean pageBean) {
    	return zhangDAO.findPageInfoZhang1(zhang, pageBean);	}	public Integer getCount1(Zhang zhang) {
    	return zhangDAO.getCount1(zhang);	}	public List<Zhang> getAllZhang() {
    	return zhangDAO.getAllZhang();	}	
}	

AdminService.java

package com.biyeseng.service;	
import java.util.List;	import com.biyeseng.common.PageBean;	
import com.biyeseng.vo.Admin;	/*** * @author biyeseng* @company www.biyeseng.cn**/
public interface AdminService	
{
    	public void save(Admin admin);	public void update(Admin admin);	public void delete(Admin admin);	public Admin getAdmin(Admin admin);	public Admin getAdmin(Long id);	public List<Admin> findPageInfoAdmin(Admin admin,PageBean pageBean);	public Integer getCount(Admin admin);	public List<Admin> findPageInfoAdmin1(Admin admin,PageBean pageBean);	public Integer getCount1(Admin admin);	public List<Admin> getAllAdmin();	
}	

3、Action类
ZhangWebAction.java

package com.biyeseng.action;	import java.util.Calendar;	
import java.util.Date;	
import java.util.List;	import javax.servlet.http.HttpServletRequest;	import org.apache.commons.lang.StringUtils;	
import org.apache.log4j.Logger;	
import org.apache.struts2.ServletActionContext;	import com.biyeseng.common.Constants;	
import com.biyeseng.common.DataSource;import com.biyeseng.common.PageBean;	import com.biyeseng.service.TongService;
import com.biyeseng.service.ZhangService;	
import com.biyeseng.vo.User;
import com.biyeseng.vo.Tong;
import com.biyeseng.vo.Zhang;	import com.opensymphony.xwork2.ActionSupport;	/*** 记账Action* @author biyeseng* @company www.biyeseng.cn**/
public class ZhangWebAction extends ActionSupport {
    	/** * Service层实例 */	private ZhangService zhangService;	private TongService tongService;	/** * 日志 */	private Logger log = Logger.getLogger(this.getClass());	private Zhang zhang = new Zhang();	private Long id;	private String qmonth;private String qyear;@SuppressWarnings("unchecked")	public String queryZhang() {
    	log.debug("queryZhang" + "开始");	HttpServletRequest request = ServletActionContext.getRequest();	initSelect(request);	int resultSize = 0;	PageBean pageBean = null;	resultSize = zhangService.getCount(zhang);	pageBean = PageBean.getPageBean("zhang",	resultSize, request);	pageBean.setPageSize(10);	List list = zhangService.findPageInfoZhang(zhang, pageBean);	request.setAttribute("zhang_list", list);	log.debug("queryZhang" + "结束");	return Constants.LIST;	}	/** * * 进入增加界面 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String toAddZhang() {
    	log.debug("toAddZhang" + "开始");	HttpServletRequest request = ServletActionContext.getRequest();	initSelect(request);	Date date = new Date();	log.debug("toAddZhang" + "结束");	return Constants.ADD;	}	/** * * 增加 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String addZhang() {
    	log.debug("addZhang" + "开始");	try {
    	HttpServletRequest request = ServletActionContext.getRequest();	User user=(User) request.getSession().getAttribute("currentUser");zhang.setUser(user.getName());zhang.setRname(user.getRname());zhangService.save(zhang);	Tong tongs=new Tong();tongs.setUser(user.getName());String date=zhang.getDate();String year=date.split("-")[0];String month=date.split("-")[1];tongs.setYear(year);tongs.setMonth(month);List<Tong> list=tongService.findPageInfoTong(tongs, null);if(list!=null && list.size()>0){
    Tong to=list.get(0);if(zhang.getType().equals("出账")){
    to.setZhi(to.getZhi()+zhang.getCount());}else{
    to.setShou(to.getShou()+zhang.getCount());}tongService.update(to);}else{
    Tong to=new Tong();to.setDate(zhang.getDate());to.setKind(zhang.getKind());to.setMonth(month);to.setYear(year);to.setType(zhang.getType());to.setUser(user.getName());if(zhang.getType().equals("出账")){
    to.setZhi(zhang.getCount());to.setShou(0.0f);}else{
    to.setShou(zhang.getCount());to.setZhi(0.0f);}tongService.save(to);}zhang = new Zhang();	} catch (Exception e) {
    	e.printStackTrace();	log.error("addZhang failed" + zhang.toString());	}	log.debug("addZhang" + "结束");	return queryZhang();	}	/** * * 删除 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String delZhang() {
    	log.debug("delZhang" + "开始");	try {
    	zhang.setId(id);	zhangService.delete(zhang);	zhang = new Zhang();	} catch (Exception e) {
    	log.error("delZhang failed" + zhang.toString());	}	log.debug("delZhang" + "结束");	return queryZhang();	}	/** * * 进入编辑界面 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String toEditZhang() {
    	log.debug("toEditZhang" + "开始");	HttpServletRequest request = ServletActionContext.getRequest();	zhang = zhangService.getZhang(id);	initSelect(request);	log.debug("toEditZhang" + "结束");	return Constants.EDIT;	}	/** * * 进入调整访问周期界面 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String tomodifyZQ() {
    	log.debug("tomodifyZQ" + "开始");	HttpServletRequest request = ServletActionContext.getRequest();	zhang = zhangService.getZhang(id);	initSelect(request);	log.debug("tomodifyZQ" + "结束");	return "tomodifyZQ";	}	/** * * 查看信息 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String viewZhang() {
    	log.debug("viewZhang" + "开始");	zhang = zhangService.getZhang(id);	log.debug("viewZhang" + "结束");	return Constants.VIEW;	}	/** * * 编辑 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String editZhang() {
    	log.debug("editZhang" + "开始");	try {
    	zhangService.update(zhang);	zhang = new Zhang();	} catch (Exception e) {
    	log.error("editZhang failed" + zhang.toString());	}	log.debug("editZhang" + "结束");	return queryZhang();	}	public String queryYue(){
    HttpServletRequest request = ServletActionContext.getRequest();	//request.setAttribute("messageInfo", "用户名或密码错误!");Calendar cal = Calendar.getInstance();// 使用日历类String year = cal.get(Calendar.YEAR)+"";User user=(User) request.getSession().getAttribute("currentUser");String userName=user.getName();Tong tong=new Tong();tong.setYear(year);tong.setMonth(qmonth);tong.setUser(userName);List<Tong> list=tongService.findPageInfoTong(tong, null);if(list!=null&&list.size()>0){
    Tong t=list.get(0);String info="<set name='出账' value='"+t.getZhi()+"' /><set name='入账' value='"+t.getShou()+"' />";request.setAttribute("data", info);}else{
    request.setAttribute("messageInfo", year+"-"+qmonth+"月没有数据!");request.setAttribute("data", "");}return "qylist";}public String queryYear(){
    HttpServletRequest request = ServletActionContext.getRequest();	//request.setAttribute("messageInfo", "用户名或密码错误!");User user=(User) request.getSession().getAttribute("currentUser");String userName=user.getName();Tong tong=new Tong();if(qyear==null||qyear.trim().length()==0){
    Calendar cal = Calendar.getInstance();// 使用日历类String year = cal.get(Calendar.YEAR)+"";tong.setYear(year);}else{
    tong.setYear(qyear);}tong.setUser(userName);List<Tong> list=tongService.findPageInfoTong(tong, null);if(list!=null&&list.size()>0){
    String category="";String setchu="";String setru="";for(Tong t:list){
    category=category+"<category label='"+t.getMonth()+"月' />";setchu=setchu+"<set value='"+t.getZhi()+"' />";setru=setru+"<set value='"+t.getShou()+"' />";}String xmls= "<categories>"+category+"</categories>"+ "<dataset seriesName='出账'>"+setchu+"</dataset>"+ "<dataset seriesName='入账'>"+setru+"</dataset>";request.setAttribute("data", xmls);}else{
    request.setAttribute("messageInfo", qyear+"年没有数据!");request.setAttribute("data", "");}return "qnlist";}/** * @param ZhangService * the ZhangService to set */	public void setZhangService(ZhangService zhangService) {
    	this.zhangService = zhangService;	}	public Zhang getZhang() {
    	return zhang;	}	public void setZhang(Zhang zhang) {
    	this.zhang = zhang;	}	public Long getId() {
    	return id;	}	public void setId(Long id) {
    	this.id = id;	}	public TongService getTongService() {
    return tongService;}public void setTongService(TongService tongService) {
    this.tongService = tongService;}public void initSelect(HttpServletRequest request) {
    	request.setAttribute("ztype", DataSource.TYPE);request.setAttribute("zkind", DataSource.KIND);System.out.println("---------------");}public String getQmonth() {
    return qmonth;}public void setQmonth(String qmonth) {
    this.qmonth = qmonth;}public String getQyear() {
    return qyear;}public void setQyear(String qyear) {
    this.qyear = qyear;}	}	

AdminWebAction.java

package com.biyeseng.action;	import java.util.Calendar;	
import java.util.Date;	
import java.util.List;	import javax.servlet.http.HttpServletRequest;	import org.apache.commons.lang.StringUtils;	
import org.apache.log4j.Logger;	
import org.apache.struts2.ServletActionContext;	import com.biyeseng.common.Constants;	import com.biyeseng.common.PageBean;	import com.biyeseng.service.AdminService;	
import com.biyeseng.vo.Admin;	import com.opensymphony.xwork2.ActionSupport;	/*** 管理员* @author biyeseng* @company www.biyeseng.cn**/
public class AdminWebAction extends ActionSupport {
    	/** * Service层实例 */	private AdminService adminService;	/** * 日志 */	private Logger log = Logger.getLogger(this.getClass());	private Admin admin = new Admin();	private Long id;	@SuppressWarnings("unchecked")	public String queryAdmin() {
    	log.debug("queryAdmin" + "开始");	HttpServletRequest request = ServletActionContext.getRequest();	initSelect(request);	int resultSize = 0;	PageBean pageBean = null;	// Loginuser user = (Loginuser) request.getSession().getAttribute("currentUser"); resultSize = adminService.getCount(admin);pageBean = PageBean.getPageBean("admin",	resultSize, request);	pageBean.setPageSize(10);List list = adminService.findPageInfoAdmin(admin, pageBean);	request.setAttribute("admin_list", list);	log.debug("queryAdmin" + "结束");	return Constants.LIST;	}	/** * * 进入增加界面 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String toAddAdmin() {
    	log.debug("toAddAdmin" + "开始");	HttpServletRequest request = ServletActionContext.getRequest();	initSelect(request);	Date date = new Date();	log.debug("toAddAdmin" + "结束");	return Constants.ADD;	}	/** * * 增加 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String addAdmin() {
    	log.debug("addAdmin" + "开始");	try {
    	Admin admins=new Admin();admins.setName(admin.getName());List list = adminService.findPageInfoAdmin(admins, null);if (list != null && list.size() > 0) {
    HttpServletRequest request = ServletActionContext.getRequest();request.setAttribute("messageInfo", "用户名已经存在!");return toAddAdmin();}adminService.save(admin);	admin = new Admin();	} catch (Exception e) {
    	e.printStackTrace();	log.error("addAdmin failed" + admin.toString());	}	log.debug("addAdmin" + "结束");	return queryAdmin();	}	/** * * 删除 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String delAdmin() {
    	log.debug("delAdmin" + "开始");	try {
    	admin.setId(id);	adminService.delete(admin);	admin = new Admin();	} catch (Exception e) {
    	log.error("delAdmin failed" + admin.toString());	}	log.debug("delAdmin" + "结束");	return queryAdmin();	}	/** * * 进入编辑界面 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String toEditAdmin() {
    	log.debug("toEditAdmin" + "开始");	HttpServletRequest request = ServletActionContext.getRequest();	admin = adminService.getAdmin(id);	initSelect(request);	log.debug("toEditAdmin" + "结束");	return Constants.EDIT;	}	/** * * 进入调整访问周期界面 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String tomodifyZQ() {
    	log.debug("tomodifyZQ" + "开始");	HttpServletRequest request = ServletActionContext.getRequest();	admin = adminService.getAdmin(id);	initSelect(request);	log.debug("tomodifyZQ" + "结束");	return "tomodifyZQ";	}	/** * * 查看信息 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String viewAdmin() {
    	log.debug("viewAdmin" + "开始");	admin = adminService.getAdmin(id);	log.debug("viewAdmin" + "结束");	return Constants.VIEW;	}	/** * * 编辑 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */	public String editAdmin() {
    	log.debug("editAdmin" + "开始");	try {
    	adminService.update(admin);	admin = new Admin();	} catch (Exception e) {
    	log.error("editAdmin failed" + admin.toString());	}	log.debug("editAdmin" + "结束");	return queryAdmin();	}	public String editMyAdmin() {
    	log.debug("editMyAdmin" + "开始");	try {
    	HttpServletRequest request = ServletActionContext.getRequest();adminService.update(admin);	request.getSession().setAttribute("currentUser", admin);admin = new Admin();	request.setAttribute("messageInfo", "修改成功!");} catch (Exception e) {
    	log.error("editMyAdmin failed" + admin.toString());	}	log.debug("editMyAdmin" + "结束");	return "my";	}	/** * @param AdminService * the AdminService to set */	public void setAdminService(AdminService adminService) {
    	this.adminService = adminService;	}	public Admin getAdmin() {
    	return admin;	}	public void setAdmin(Admin admin) {
    	this.admin = admin;	}	public Long getId() {
    	return id;	}	public void setId(Long id) {
    	this.id = id;	}	public void initSelect(HttpServletRequest request) {
    	}	}	

4、公共类
HibernateGenericDao.java

package com.biyeseng.common;import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.Clob;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;/*** * @author biyeseng* @company www.biyeseng.cn**/
@SuppressWarnings("unchecked")
public abstract class HibernateGenericDao<T> extends HibernateDaoSupport {
    protected Class<T> entityClass;private JdbcTemplate jdbcTemplate;public HibernateGenericDao() {
    entityClass = GenericsUtils.getSuperClassGenricType(getClass());}protected Class<T> getEntityClass() {
    return entityClass;}public T get(Serializable id) {
    return (T) getHibernateTemplate().get(entityClass, id);}public Object get(Serializable id,Class clazz) {
    return getHibernateTemplate().get(clazz, id);}public List<T> getAll() {
    return getHibernateTemplate().loadAll(entityClass);}public List<T> getAll(String orderBy, boolean isAsc) {
    Assert.hasText(orderBy);if(isAsc)return getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(entityClass).addOrder(Order.asc(orderBy)));elsereturn getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(entityClass).addOrder(Order.desc(orderBy)));}public List<T> getByExample(Object o) {
    List<T> results = getHibernateTemplate().findByExample(o);return results;}public void save(Object o) {
    Session session = null;try {
    session = getSession();session.save(o);session.flush();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}}public void update(Object o) {
    Session session = null;try {
    session = getSession();session.merge(o);session.flush();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}}public void saveOrUpdate(Object o) {
    Session session = null;try {
    session = getSession();session.saveOrUpdate(o);session.flush();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}}public void remove(Object o) {
    Session session = null;try {
    session = getSession();session.delete(o);session.flush();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}// getHibernateTemplate().delete(o);}public void removeById(Serializable id) {
    remove(get(id));}public void flush() {
    getHibernateTemplate().flush();}public void clear() {
    getHibernateTemplate().clear();}public Query createQuery(Session session, String hql, Object... values) {
    Assert.hasText(hql);Query query = session.createQuery(hql);for(int i = 0; i < values.length; i++) {
    query.setParameter(i, values[i]);}return query;}public Criteria createCriteria(Session session, Criterion... criterions) {
    Criteria criteria = session.createCriteria(entityClass);for(Criterion c : criterions) {
    criteria.add(c);}return criteria;}public Criteria createCriteria(Session session, String orderBy, boolean isAsc, Criterion... criterions) {
    Assert.hasText(orderBy);Criteria criteria = createCriteria(session, criterions);if(isAsc)criteria.addOrder(Order.asc(orderBy));elsecriteria.addOrder(Order.desc(orderBy));return criteria;}public List find(String hql, Object... values) {
    Assert.hasText(hql);return getHibernateTemplate().find(hql, values);}public List<T> findBy(String propertyName, Object value) throws RuntimeException {
    Assert.hasText(propertyName);Session session = null;List<T> ll = new ArrayList<T>();try {
    session = getSession();ll = createCriteria(session, Restrictions.eq(propertyName, value)).list();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}return ll;}public List<T> findBy(String propertyName, Object value, String orderBy, boolean isAsc) {
    Assert.hasText(propertyName);Assert.hasText(orderBy);Session session = null;List<T> ll = new ArrayList<T>();try {
    session = getSession();ll = createCriteria(session, orderBy, isAsc, Restrictions.eq(propertyName, value)).list();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}return ll;}public List<T> findByValues(String propertyName, Collection values) {
    Assert.hasText(propertyName);Session session = null;List<T> ll = new ArrayList<T>();try {
    session = getSession();ll = createCriteria(session, Restrictions.in(propertyName, values)).list();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}return ll;}public List<T> findByNamesAndValues(List<String> propertyNames, List values) {
    List<T> ll = new ArrayList<T>();Session session = getSession();try {
    Criteria criteria = session.createCriteria(entityClass);for(int i = 0; i < propertyNames.size(); i++) {
    String propertyName = propertyNames.get(i);Object value = values.get(i);if(value != null) {
    criteria.add(Restrictions.eq(propertyName, value));} else {
    criteria.add(Restrictions.isNull(propertyName));}}ll = criteria.list();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    releaseSession(session);}}return ll;}public T findUniqueBy(String propertyName, Object value) {
    Assert.hasText(propertyName);Session session = null;Object obj = new Object();try {
    session = getSession();obj = createCriteria(session, Restrictions.eq(propertyName, value)).uniqueResult();}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}return (T) obj;}public boolean isUnique(Object entity, String uniquePropertyNames) {
    Assert.hasText(uniquePropertyNames);Session session = null;String[] nameList = uniquePropertyNames.split(",");session = getSession();Criteria criteria = createCriteria(session).setProjection(Projections.rowCount());try {
    for(String name : nameList) {
    criteria.add(Restrictions.eq(name, PropertyUtils.getProperty(entity, name)));}String idName = getIdName(entityClass);Serializable id = getId(entity);if(id != null)criteria.add(Restrictions.not(Restrictions.eq(idName, id)));}catch(Exception e) {
    ReflectionUtils.handleReflectionException(e);}boolean result = false;try {
    result = (Integer) criteria.uniqueResult() == 0;}catch(RuntimeException e) {
    throw e;}finally {
    if(session != null) {
    this.releaseSession(session);}}return result;}public Serializable getId(Object entity) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    Assert.notNull(entity);Assert.notNull(entityClass);return (Serializable) PropertyUtils.getProperty(entity, getIdName(entityClass));}public String getIdName(Class clazz) {
    Assert.notNull(clazz);ClassMetadata meta = getSessionFactory().getClassMetadata(clazz);Assert.notNull(meta, "Class " + clazz + " not define in hibernate session factory.");String idName = meta.getIdentifierPropertyName();Assert.hasText(idName, clazz.getSimpleName() + " has no identifier property define.");return idName;}public void evit(Object entity) {
    getHibernateTemplate().evict(entity);}public void updateOrDelete(String hql) throws Exception {
    Session session = null;try {
    session = getSession();session.createQuery(hql).executeUpdate();}catch(Exception e) {
    throw e;}finally {
    if(session != null) {
    releaseSession(session);}}}public List findBySQL(String sql,List args) throws Exception {
    List list = new ArrayList();Session session = null;try {
    session = getSession();Query query = session.createSQLQuery(sql).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);setParameter(query,args);list = query.list();}catch(Exception e) {
    throw e;}finally {
    super.releaseSession(session);}return list;}public List queryByHql(String hql,List args) throws Exception {
    List list = new ArrayList();Session session = null;try {
    session = getSession();Query query = session.createQuery(hql);setParameter(query,args);list = query.list();}catch(Exception e) {
    throw e;}finally {
    if(session != null) {
    releaseSession(session);}}return list;}public List queryByHqlAll(String hql, List args) {
    return getHibernateTemplate().find(hql, args.toArray());}public List<T> queryBySQLAll(String sql, List args) {
    List<T> res = null;try {
    if(args == null){
    args = new ArrayList();}List<Map> listMap = jdbcTemplate.queryForList(sql, args.toArray());if(listMap != null && listMap.size() > 0) {
    res = new ArrayList();for(Map map : listMap) {
    T t = entityClass.newInstance();Iterator it = map.entrySet().iterator();while (it.hasNext()) {
    Map.Entry<String, Object> me = (Entry) it.next();String key = me.getKey().toLowerCase();key = StringUtils.getNameFromDB(key, false);Object value = me.getValue();if(value == null){
    continue;}if(value instanceof Timestamp){
    Date dateValue = DateUtils.parseTimestamp(value.toString());BeanUtils.setProperty(t, key, dateValue);continue;}BeanUtils.setProperty(t, key, value);}res.add(t);}}}catch(Exception ex) {
    ex.printStackTrace();return null;}return res;}public List<T> getPageInfo(PageBean pageBean,String sql,List list) {
    List<T> res = null;Session session = this.getSession();try {
    Query query = session.createSQLQuery(sql.toString()).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);if(pageBean != null) {
    // 设置开始页query.setFirstResult(pageBean.getPageSize() * (pageBean.getPageIndex() - 1));// 设置结束页query.setMaxResults(pageBean.getPageSize());}setParameter(query,list);query.list();List<Map> listMap = query.list();if(listMap != null && listMap.size() > 0) {
    res = new ArrayList();for(Map map : listMap) {
    T t = entityClass.newInstance();Iterator it = map.entrySet().iterator();while (it.hasNext()) {
    Map.Entry<String, Object> me = (Entry) it.next();String key = StringUtils.getNameFromDB(me.getKey(), false);Object value = me.getValue();if(value == null){
    continue;}if(value instanceof Timestamp){
    Date dateValue = DateUtils.parseTimestamp(value.toString());BeanUtils.setProperty(t, key, dateValue);continue;}if(value instanceof Date){
    Date dateValue = DateUtils.parseDate(value.toString());BeanUtils.setProperty(t, key, dateValue);continue;}if(value instanceof Clob){
    if(value != null){
    Clob clob = (Clob) value;String dateValue = clob.getSubString(1, (int) clob.length());BeanUtils.setProperty(t, key, dateValue);continue;}}BeanUtils.setProperty(t, key, value);}res.add(t);}}}catch(Exception re) {
    re.printStackTrace();logger.error("getPageInfo failed");return null;}finally {
    if(session != null) {
    releaseSession(session);}}return res;}public void setParameter(Query query,List args){
    if(null != args && args.size()>0){
    for(int i=0;i<args.size();i++){
    query.setParameter(i, args.get(i));}}}public Integer getCount(String sql, Object[] args) {
    return jdbcTemplate.queryForInt(sql, args);}public List select(String sql, Object[] args, RowMapper rowMapper) {
    return jdbcTemplate.query(sql, args, rowMapper);}public List select(String sql) {
    return jdbcTemplate.queryForList(sql);}public void execute(String sql){
    jdbcTemplate.execute(sql);}public JdbcTemplate getJdbcTemplate() {
    return jdbcTemplate;}public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;}}

写在最后

全部源码和详细文档,需要可加博主V交流:Code2Life2

  相关解决方案