SpringJdbc持久层封装,Spring jdbcTemplate封装,springJdbc泛型Dao,Spring baseDao封装
SpringJdbc持久层封装,Spring jdbcTemplate封装,springJdbc泛型Dao,Spring baseDao封装
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年7月6日
http://www.cnblogs.com/fanshuyao/
很久之前弄的Spring Jdbc持久化层的baseDao,现在做个记录。
基本的增、删、查、改、分页、排序都可以用,只是兼容一般,如主键必须是id,并没有深入再封装。
- package com.lqy.spring.dao.impl;
- import java.io.Serializable;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.Map;
- import org.springframework.beans.BeanWrapper;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.jdbc.core.BeanPropertyRowMapper;
- import org.springframework.jdbc.core.JdbcTemplate;
- import com.lqy.Utils.EntityUtils;
- import com.lqy.Utils.StrUtils;
- import com.lqy.spring.bean.Page;
- import com.lqy.spring.dao.BaseDao;
- import com.lqy.spring.editor.GenderEditor;
- import com.lqy.spring.entity.SqlEntity;
- import com.lqy.spring.enums.Gender;
- @SuppressWarnings({"unchecked","rawtypes"})
- public class BaseDaoImpl<T> implements BaseDao<T> {
- @Autowired
- JdbcTemplate jdbcTemplate;
- //entityClass.getSimpleName()=Person
- //entityClass.getName()=com.lqy.spring.c3p0.beans.Person
- protected Class<T> entityClass = (Class<T>) EntityUtils.getEntityClass(this.getClass());
- //private RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(entityClass);
- private BeanPropertyRowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(entityClass){
- @Override
- protected void initBeanWrapper(BeanWrapper bw) {
- bw.registerCustomEditor(Gender.class, new GenderEditor());
- super.initBeanWrapper(bw);
- }
- };
- /**
- * 获取实体
- * @param id 对象的id(Serializable)
- * @return T 对象
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public T get(Serializable id) {
- String sql = getSql() + "and id=? ";
- return (T)jdbcTemplate.queryForObject(sql, rowMapper, id);
- }
- /**
- * 查询
- * @return List<T>
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public List<T> query() {
- return (List<T>) jdbcTemplate.query(getSql(), rowMapper);
- }
- /**
- * 查询
- * @param page 分页参数
- * @param whereSql 查询条件(例:o.name=?)
- * @param params 查询条件对应的参数(List<Object>)
- * @return List<T>
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public List<T> query(Page page, String whereSql, List<Object> params) {
- List<Object> paramList = new ArrayList<Object>();
- if(!StrUtils.isEmpty(whereSql) && !StrUtils.isEmpty(params)){
- for (Object object : params) {
- if(object instanceof Enum){
- paramList.add(((Enum)object).ordinal());
- }else{
- paramList.add(object);
- }
- }
- }
- String sql = getSql(page, whereSql, null);
- dealPage(page, sql, paramList);
- if(!StrUtils.isEmpty(page)){
- paramList.add(page.getOffSize());
- paramList.add(page.getCurrentSize());
- }
- return (List<T>)jdbcTemplate.query(sql, rowMapper, paramList.toArray());
- }
- /**
- * 查询
- * @param page 分页参数
- * @param orderby 排序条件(LinkedHashMap<String, String>)
- * @return List<T>
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public List<T> query(Page page, LinkedHashMap<String, String> orderby) {
- List<Object> paramsList = new ArrayList<Object>();
- String sql = getSql(page, null, orderby);
- dealPage(page, sql, paramsList);
- if(!StrUtils.isEmpty(page)){
- paramsList.add(page.getOffSize());
- paramsList.add(page.getCurrentSize());
- }
- return (List<T>)jdbcTemplate.query(sql, rowMapper, paramsList.toArray());
- }
- /**
- * 查询
- * @param page 分页参数
- * @param whereSql 查询条件(例:o.name=?)
- * @param params 查询条件对应的参数(List<Object>)
- * @param orderby 排序条件(LinkedHashMap<String, String>)
- * @return List<T>
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public List<T> query(Page page, String whereSql, List<Object> params, LinkedHashMap<String, String> orderby) {
- List<Object> paramsList = new ArrayList<Object>();
- if(!StrUtils.isEmpty(whereSql) && !StrUtils.isEmpty(params)){
- for (Object object : params) {
- if(object instanceof Enum){
- paramsList.add(((Enum)object).ordinal());
- }else{
- paramsList.add(object);
- }
- }
- }
- String sql = getSql(page, whereSql, orderby);
- //System.out.println("sql ="+sql);
- dealPage(page, sql, paramsList);
- if(!StrUtils.isEmpty(page)){
- paramsList.add(page.getOffSize());
- paramsList.add(page.getCurrentSize());
- }
- return (List<T>)jdbcTemplate.query(sql, rowMapper, paramsList.toArray());
- }
- /**
- * 更新
- * @param sql 自定义更新sql
- * @param params 查询条件对应的参数(List<Object>)
- * @return int 更新的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int update(String sql, List<Object> params) {
- //String sql="update person set name=? where id=?";
- return jdbcTemplate.update(sql, params.toArray());
- }
- /**
- * 更新(先从数据库取出来再更新)
- * @param t 更新的对象
- * @return int 更新的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int update(T t) throws Exception{
- SqlEntity sqlEntity = getUpdateSql(t);
- //System.out.println("=====sqlEntity.getSql()="+sqlEntity.getSql());
- return jdbcTemplate.update(sqlEntity.getSql(), sqlEntity.getParams().toArray());
- }
- /**
- * 更新(通过模板更新,把符合template条件的数据都更新为value对象中的值)
- * @param t 更新的对象
- * @return int 更新的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int update(T value,T template) throws Exception{
- SqlEntity sqlEntity = getUpdateSql(value,template);
- //System.out.println("=====update(T value,T template) sqlEntity.getSql()="+sqlEntity.getSql());
- return jdbcTemplate.update(sqlEntity.getSql(), sqlEntity.getParams().toArray());
- }
- /**
- * 保存
- * @param t 保存的对象
- * @return int 保存的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int save(T t) throws Exception{
- SqlEntity sqlEntity = getSaveSql(t);
- return jdbcTemplate.update(sqlEntity.getSql(), sqlEntity.getParams().toArray());
- };
- /**
- * 保存
- * @param sql 自定义保存sql
- * @param params 查询条件对应的参数(List<Object>)
- * @return int 保存的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int save(String sql, List<Object> params) {
- //String sql="INSERT INTO person (`name`,age,create_time) VALUES(?,?,?);";
- return jdbcTemplate.update(sql, params.toArray());
- }
- /**
- * 删除
- * @param id 对象的id(Serializable)
- * @return int 删除的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int delete(Serializable id) {
- String sql="delete from " + StrUtils.changeName(this.entityClass.getSimpleName()) + " where id=?";
- return jdbcTemplate.update(sql, id);
- }
- @SuppressWarnings("deprecation")
- @Override
- public int getCount(String whereSql, Object[] objects){
- String entityName = this.entityClass.getSimpleName();
- StringBuffer sql = new StringBuffer("select count(*) from ");
- sql.append(StrUtils.changeName(entityName));
- sql.append(" o ").append(whereSql);
- //System.out.println("getCount sql.toString()="+sql.toString());
- //return jdbcTemplate.queryForInt(sql.toString(), entityClass);
- return jdbcTemplate.queryForInt(sql.toString(), objects);
- }
- protected String getSql(){
- String entityName = this.entityClass.getSimpleName();
- StringBuffer sql = new StringBuffer("select * from ");
- sql.append(StrUtils.changeName(entityName));
- sql.append(" o where 1=1 ");
- return sql.toString();
- }
- protected String getSql(String whereSql){
- String entityName = this.entityClass.getSimpleName();
- StringBuffer sql = new StringBuffer("select * from ");
- sql.append(StrUtils.changeName(entityName));
- sql.append(" o where 1=1 ");
- if(!StrUtils.isEmpty(whereSql)){
- sql.append(" ").append(whereSql);
- }
- return sql.toString();
- }
- /**
- * 获取sql
- * @param page 分页参数,如果为空,则不在sql增加limit ?,?
- * @param orderby 排序参数,如果为空,则不在sql增加ORDER BY
- * @param whereSql 查询条件参数,如果为空,则不在sql增加 and name=?
- * @return sql
- */
- protected String getSql(Page page, String whereSql, Map<String,String> orderby){
- String entityName = this.entityClass.getSimpleName();
- StringBuffer sql = new StringBuffer("select * from ");
- sql.append(StrUtils.changeName(entityName));
- sql.append(" o where 1=1 ");
- if(!StrUtils.isEmpty(whereSql)){
- sql.append(" ").append(whereSql);
- }
- if(!StrUtils.isEmpty(orderby)){
- sql.append(" ORDER BY ");
- for (String string : orderby.keySet()) {
- String value = orderby.get(string);
- if(StrUtils.isEmpty(value)){
- value = "ASC";
- }
- sql.append("o.").append(string).append(" ").append(value.toUpperCase()).append(",");
- }
- if(sql.indexOf(",") > -1){
- sql.deleteCharAt(sql.length()-1);
- }
- }
- if(!StrUtils.isEmpty(page)){
- sql.append(" limit ?,? ");
- }
- //System.out.println("------sql.toString()="+sql.toString());
- return sql.toString();
- }
- private SqlEntity getUpdateSql(T t) throws Exception{
- SqlEntity sqlEntity = new SqlEntity();
- sqlEntity.setParams(new ArrayList<Object>());
- Field[] fields = entityClass.getDeclaredFields();
- StringBuffer sql = new StringBuffer("");
- sql.append("update ").append(StrUtils.changeName(entityClass.getSimpleName())).append(" o set ");
- for (Field field : fields) {
- StringBuffer methodName = new StringBuffer("");
- //System.out.println("===field.getType()="+field.getType());
- if(field.getType() == boolean.class){
- if(field.getName().contains("is")){
- methodName.append(field.getName());
- }else{
- methodName.append("is").append(StrUtils.firstCodeToUpperCase(field.getName()));
- }
- }else{
- methodName.append("get").append(StrUtils.firstCodeToUpperCase(field.getName()));
- }
- if(!"id".equals(field.getName())){
- Method method = entityClass.getMethod(methodName.toString(), new Class[]{});
- Object objectValue = method.invoke(t, new Object[]{});
- if(objectValue instanceof Enum){
- sqlEntity.getParams().add(((Enum)objectValue).ordinal());
- }else{
- sqlEntity.getParams().add(objectValue);
- }
- sql.append(" o.").append(StrUtils.changeName(field.getName())).append("= ?,");
- }
- }
- if(sql.indexOf(",") > -1){
- sql.deleteCharAt(sql.length() - 1);
- }
- sql.append(" where o.id=?");
- Method idMethod = entityClass.getMethod("getId", new Class[]{});
- sqlEntity.getParams().add(idMethod.invoke(t, new Object[]{}));
- sqlEntity.setSql(sql.toString());
- return sqlEntity;
- }
- private SqlEntity getUpdateSql(T value, T template) throws Exception{
- SqlEntity sqlEntity = new SqlEntity();
- sqlEntity.setParams(new ArrayList<Object>());
- Field[] fields = entityClass.getDeclaredFields();
- StringBuffer sql = new StringBuffer("");
- sql.append("update ").append(StrUtils.changeName(entityClass.getSimpleName())).append(" o set ");
- StringBuffer whereSql = new StringBuffer(" where ");
- for (Field field : fields) {
- StringBuffer methodName = new StringBuffer("");
- //System.out.println("===field.getType()="+field.getType());
- if(field.getType() == boolean.class){
- if(field.getName().contains("is")){
- methodName.append(field.getName());
- }else{
- methodName.append("is").append(StrUtils.firstCodeToUpperCase(field.getName()));
- }
- }else{
- methodName.append("get").append(StrUtils.firstCodeToUpperCase(field.getName()));
- }
- if(!"id".equals(field.getName())){
- Method method = entityClass.getMethod(methodName.toString(), new Class[]{});
- Object objectValue = method.invoke(value, new Object[]{});
- if(!StrUtils.isEmpty(objectValue)){
- if(objectValue instanceof Enum){
- sqlEntity.getParams().add(((Enum)objectValue).ordinal());
- }else{
- sqlEntity.getParams().add(objectValue);
- }
- //sqlEntity.getParams().add(objectValue);
- sql.append(" o.").append(StrUtils.changeName(field.getName())).append("= ?,");
- }
- }
- }
- for (Field field : fields) {
- StringBuffer methodName = new StringBuffer("");
- if(field.getType() == boolean.class){
- if(field.getName().contains("is")){
- methodName.append(field.getName());
- }else{
- methodName.append("is").append(StrUtils.firstCodeToUpperCase(field.getName()));
- }
- }else{
- methodName.append("get").append(StrUtils.firstCodeToUpperCase(field.getName()));
- }
- Method method = entityClass.getMethod(methodName.toString(), new Class[]{});
- Object objectValue = method.invoke(template, new Object[]{});
- if(!StrUtils.isEmpty(objectValue)){
- sqlEntity.getParams().add(objectValue);
- whereSql.append(" o.").append(StrUtils.changeName(field.getName())).append("= ? and");
- }
- }
- if(sql.indexOf(",") > -1){
- sql.deleteCharAt(sql.length() - 1);
- }
- if(whereSql.indexOf("and") > -1){
- sql.append(whereSql.substring(0, whereSql.length()-3));
- whereSql = new StringBuffer();
- }else{
- sql.append(whereSql);
- }
- sqlEntity.setSql(sql.toString());
- return sqlEntity;
- }
- private SqlEntity getSaveSql(T t) throws Exception{
- SqlEntity sqlEntity = new SqlEntity();
- sqlEntity.setParams(new ArrayList<Object>());
- Field[] fields = entityClass.getDeclaredFields();
- StringBuffer sql = new StringBuffer("");
- sql.append("insert into ").append(StrUtils.changeName(entityClass.getSimpleName())).append(" ( ");
- int paramLength = 0;
- for (Field field : fields) {
- StringBuffer methodName = new StringBuffer("");
- if(field.getType() == boolean.class){
- if(field.getName().contains("is")){
- methodName.append(field.getName());
- }else{
- methodName.append("is").append(StrUtils.firstCodeToUpperCase(field.getName()));
- }
- }else{
- methodName.append("get").append(StrUtils.firstCodeToUpperCase(field.getName()));
- }
- Method method = entityClass.getMethod(methodName.toString(), new Class[]{});
- Object value = method.invoke(t, new Object[]{});
- if(!StrUtils.isEmpty(value)){
- if(value instanceof Enum){
- sqlEntity.getParams().add(((Enum) value).ordinal());
- }else{
- sqlEntity.getParams().add(value);
- }
- sql.append("`").append(StrUtils.changeName(field.getName())).append("`").append(",");
- paramLength ++;
- }
- }
- if(sql.indexOf(",") > -1){
- sql.deleteCharAt(sql.length() - 1);
- }
- sql.append(") values(");
- for (int i=0;i<paramLength;i++) {
- sql.append("?,");
- }
- if(sql.indexOf(",") > -1){
- sql.deleteCharAt(sql.length() - 1);
- }
- sql.append(")");
- //System.out.println("sql.toString()="+sql.toString());
- sqlEntity.setSql(sql.toString());
- return sqlEntity;
- }
- private void dealPage(Page page, String sql, List<Object> params){
- String whereSql = "";
- if(sql != null && !sql.trim().equals("")){
- int whereIndex = sql.toLowerCase().indexOf("where");
- int orderIndex = sql.toLowerCase().indexOf("order");
- int limitIndex = sql.toLowerCase().indexOf("limit");
- if(whereIndex > -1){
- whereSql = sql.substring(whereIndex, sql.length());
- orderIndex = whereSql.toLowerCase().indexOf("order");
- }
- if(whereIndex > -1 && orderIndex > -1){
- whereSql = whereSql.substring(0, orderIndex - 1);
- limitIndex = whereSql.toLowerCase().indexOf("limit");
- }
- if(whereIndex > -1 && limitIndex > -1){
- whereSql = whereSql.substring(0, limitIndex - 1);
- }
- }
- if(page.getTotalSizeNew()){
- page.setTotalSize(getCount(whereSql, params.toArray()));
- }
- setPage(page);
- }
- private void setPage(Page page){
- page.setTotalPages(page.getTotalSize()%page.getCurrentSize()==0?page.getTotalSize()/page.getCurrentSize():(page.getTotalSize()/page.getCurrentSize()+1));
- page.setCurrentPage(page.getOffSize()/page.getCurrentSize()+1);
- }
- }
- package com.lqy.spring.dao;
- import java.io.Serializable;
- import java.util.LinkedHashMap;
- import java.util.List;
- import com.lqy.spring.bean.Page;
- public interface BaseDao<T> {
- public T get(Serializable id);
- public List<T> query();
- public List<T> query(Page page, String whereSql, List<Object> params);
- public List<T> query(Page page, LinkedHashMap<String, String> orderby);
- public List<T> query(Page page, String whereSql, List<Object> params, LinkedHashMap<String, String> orderby);
- public int update(String sql, List<Object> params);
- public int update(T t) throws Exception;
- public int update(T value,T template) throws Exception;
- public int save(T t) throws Exception;
- public int save(String sql, List<Object> params);
- public int delete(Serializable id);
- public int getCount(String whereSql, Object[] objects);
- }
- package com.lqy.spring.service.impl;
- import java.io.Serializable;
- import java.util.LinkedHashMap;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.transaction.annotation.Isolation;
- import org.springframework.transaction.annotation.Transactional;
- import com.lqy.spring.bean.Page;
- import com.lqy.spring.dao.BaseDao;
- import com.lqy.spring.service.BaseService;
- @Transactional
- public class BaseServiceImpl<T> implements BaseService<T> {
- @Autowired
- BaseDao<T> baseDao;
- /**
- * 获取实体
- * @param id 对象的id(Serializable)
- * @return T 对象
- * @author lqy
- * @since 2015-10-18
- */
- @Transactional(isolation=Isolation.READ_COMMITTED,
- readOnly=true)
- @Override
- public T get(Serializable id) {
- return baseDao.get(id);
- }
- /**
- * 查询
- * @return List<T>
- * @author lqy
- * @since 2015-10-18
- */
- @Transactional(isolation=Isolation.READ_COMMITTED,readOnly=true)
- @Override
- public List<T> query() {
- return baseDao.query();
- }
- /**
- * 查询
- * @param page 分页参数
- * @param whereSql 查询条件(例:o.name=?)
- * @param params 查询条件对应的参数(List<Object>)
- * @return List<T>
- * @author lqy
- * @since 2015-10-18
- */
- @Transactional(isolation=Isolation.READ_COMMITTED,
- readOnly=true)
- @Override
- public List<T> query(Page page, String whereSql, List<Object> params) {
- return baseDao.query(page, whereSql, params);
- }
- /**
- * 查询
- * @param page 分页参数
- * @param orderby 排序条件(LinkedHashMap<String, String>)
- * @return List<T>
- * @author lqy
- * @since 2015-10-18
- */
- @Transactional(isolation=Isolation.READ_COMMITTED,
- readOnly=true)
- @Override
- public List<T> query(Page page, LinkedHashMap<String, String> orderby) {
- return baseDao.query(page, orderby);
- }
- /**
- * 查询
- * @param page 分页参数
- * @param whereSql 查询条件(例:o.name=?)
- * @param params 查询条件对应的参数(List<Object>)
- * @param orderby 排序条件(LinkedHashMap<String, String>)
- * @return List<T>
- * @author lqy
- * @since 2015-10-18
- */
- @Transactional(isolation=Isolation.READ_COMMITTED,
- readOnly=true)
- @Override
- public List<T> query(Page page, String whereSql, List<Object> params,
- LinkedHashMap<String, String> orderby) {
- return baseDao.query(page, whereSql, params, orderby);
- }
- /**
- * 更新
- * @param sql 自定义更新sql
- * @param params 查询条件对应的参数(List<Object>)
- * @return int 更新的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int update(String sql, List<Object> params) {
- return baseDao.update(sql, params);
- }
- /**
- * 更新(先从数据库取出来再更新)
- * @param t 更新的对象
- * @return int 更新的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int update(T t) throws Exception {
- return baseDao.update(t);
- }
- /**
- * 更新(通过模板更新,把符合template条件的数据都更新为value对象中的值)
- * @param t 更新的对象
- * @return int 更新的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int update(T value,T template) throws Exception{
- return baseDao.update(value,template);
- }
- /**
- * 保存
- * @param t 保存的对象
- * @return int 保存的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int save(T t) throws Exception {
- return baseDao.save(t);
- }
- /**
- * 保存
- * @param sql 自定义保存sql
- * @param params 查询条件对应的参数(List<Object>)
- * @return int 保存的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int save(String sql, List<Object> params) {
- return baseDao.save(sql, params);
- }
- /**
- * 删除
- * @param id 对象的id(Serializable)
- * @return int 删除的数量
- * @author lqy
- * @since 2015-10-18
- */
- @Override
- public int delete(Serializable id) {
- return baseDao.delete(id);
- }
- }
- package com.lqy.spring.service;
- import java.io.Serializable;
- import java.util.LinkedHashMap;
- import java.util.List;
- import com.lqy.spring.bean.Page;
- public interface BaseService<T> {
- public T get(Serializable id);
- public List<T> query();
- public List<T> query(Page page, String whereSql, List<Object> params);
- public List<T> query(Page page, LinkedHashMap<String, String> orderby);
- public List<T> query(Page page, String whereSql, List<Object> params, LinkedHashMap<String, String> orderby);
- public int update(String sql, List<Object> params);
- public int update(T t) throws Exception;
- public int update(T value,T template) throws Exception;
- public int save(T t) throws Exception;
- public int save(String sql, List<Object> params);
- public int delete(Serializable id);
- }
- package com.lqy.spring.bean;
- public class Page {
- private int currentSize;
- private int offSize;
- private int totalSize;
- private int totalPages;
- private int currentPage;
- private Boolean totalSizeNew;
- /**
- * 分页构造函数
- * @author lqy
- * @since 2015-10-22
- */
- public Page() {
- super();
- }
- /**
- * 分页构造函数
- * @param currentSize
- * @param offSize
- * @author lqy
- * @since 2015-10-22
- */
- public Page(int currentSize, int offSize) {
- super();
- this.currentSize = currentSize;
- this.offSize = offSize;
- }
- /**
- * 分页构造函数
- * @param currentSize
- * @param offSize
- * @param totalSizeNew
- * @author lqy
- * @since 2015-10-22
- */
- public Page(int currentSize, int offSize, boolean totalSizeNew) {
- super();
- this.currentSize = currentSize;
- this.offSize = offSize;
- this.totalSizeNew = totalSizeNew;
- }
- /**
- * 分页构造函数
- * @param currentSize
- * @param offSize
- * @param totalSize
- * @param totalPages
- * @param currentPage
- * @param totalSizeNew
- * @author lqy
- * @since 2015-10-22
- */
- public Page(int currentSize, int offSize, int totalSize, int totalPages,
- int currentPage, boolean totalSizeNew) {
- super();
- this.currentSize = currentSize;
- this.offSize = offSize;
- this.totalSize = totalSize;
- this.totalPages = totalPages;
- this.currentPage = currentPage;
- this.totalSizeNew = totalSizeNew;
- }
- public int getCurrentSize() {
- return currentSize;
- }
- public void setCurrentSize(int currentSize) {
- this.currentSize = currentSize;
- }
- public int getOffSize() {
- return offSize;
- }
- public void setOffSize(int offSize) {
- this.offSize = offSize;
- }
- public int getTotalSize() {
- return totalSize;
- }
- public void setTotalSize(int totalSize) {
- this.totalSize = totalSize;
- }
- public int getTotalPages() {
- return totalPages;
- }
- public void setTotalPages(int totalPages) {
- this.totalPages = totalPages;
- }
- public int getCurrentPage() {
- return currentPage;
- }
- public void setCurrentPage(int currentPage) {
- this.currentPage = currentPage;
- }
- public Boolean getTotalSizeNew() {
- return totalSizeNew;
- }
- public void setTotalSizeNew(Boolean totalSizeNew) {
- this.totalSizeNew = totalSizeNew;
- }
- @Override
- public String toString() {
- return "Page [currentSize=" + currentSize + ", offSize=" + offSize
- + ", totalSize=" + totalSize + ", totalPages=" + totalPages
- + ", currentPage=" + currentPage + ", totalSizeNew="
- + totalSizeNew + "]";
- }
- }
使用的一个例子:
- package com.lqy.spring.service.impl;
- import java.util.ArrayList;
- import java.util.LinkedHashMap;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import com.lqy.Utils.StrUtils;
- import com.lqy.exception.PersonMoneyNotEnoughException;
- import com.lqy.spring.bean.Page;
- import com.lqy.spring.bean.Person;
- import com.lqy.spring.dao.PersonDao;
- import com.lqy.spring.service.BookService;
- import com.lqy.spring.service.PersonService;
- @Service
- public class PersonServiceImpl extends BaseServiceImpl<Person> implements PersonService {
- @Autowired
- PersonDao personDao;
- @Autowired
- BookService bookService;
- @Override
- public List<Person> getPersons(Page page, String name, Integer age, Integer statusType){
- StringBuffer whereSql = new StringBuffer();
- List<Object> params = new ArrayList<Object>();
- LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
- if(!StrUtils.isEmpty(name)){
- whereSql.append(" and o.name like ?");
- params.add("%"+name+"%");
- }
- if(!StrUtils.isEmpty(age)){
- whereSql.append(" and o.age = ?");
- params.add(age);
- }
- if(!StrUtils.isEmpty(statusType)){
- whereSql.append(" and o.statusType = ?");
- params.add(statusType);
- }
- orderby.put("create_time", "desc");
- orderby.put("id", "desc");
- return personDao.query(page, whereSql.toString(), params, orderby);
- }
- @Transactional
- public int buyBook(Integer personId, Double price) throws Exception{
- int result = -1;
- Person person = personDao.get(personId);
- if(!StrUtils.isEmpty(person)){
- Double leftMoney = person.getMoney() - price;
- if(leftMoney >= 0){
- person.setMoney(leftMoney);
- result = personDao.update(person);
- }else{
- throw new PersonMoneyNotEnoughException();
- }
- }
- return result;
- }
- @Transactional
- @Override
- public int buyBook(Integer personId, Integer bookId, Integer amount) throws Exception{
- int result = -1;
- Person person = personDao.get(personId);
- if(!StrUtils.isEmpty(person)){
- Double price = bookService.getBooksPrices(bookId, amount);
- Double leftMoney = person.getMoney() - price;
- if(leftMoney >= 0){
- person.setMoney(leftMoney);
- personDao.update(person);
- bookService.sellBooks(bookId, amount);
- result = 1;
- }else{
- throw new PersonMoneyNotEnoughException();
- }
- }
- return result;
- }
- }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年7月6日
http://www.cnblogs.com/fanshuyao/
SpringJdbc持久层封装,Spring jdbcTemplate封装,springJdbc泛型Dao,Spring baseDao封装的更多相关文章
- spring学习(四)spring 持久层的封装
持久层:所谓“持久层”,也就是在系统逻辑层面上,专著于实现数据持久化的一个相对独立的领域(Domain),是把数据保存到可掉电式存储设备中.持久层是负责向(或者从)一个或者多个数据存储器中存储(或者获 ...
- 对spring 对持久层的支持和数据库连接池的理解
1.spring对持久层的支持在于,得到数据库连接之后操作上的封装,将操作简化了.也就是说以后操作sql语句就用XXXTemplate(就是一个工具类)对象了. 2.数据库连接池的作用只在于得到数据库 ...
- 【Spring】Spring JdbcTemplate
Spring JdbcTemplate 文章源码 JdbcTemplate 概述 它是 Spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装.Spring 框架提供了很多的操 ...
- Spring——JdbcTemplate
一.JdbcTemplate介绍: 为了使 JDBC 更加易于使用,Spring 在 JDBCAPI 上定义了一个抽象层, 以此建立一个JDBC存取框架,Spring Boot Spring Data ...
- SSH三种框架及表示层、业务层和持久层的理解
Struts(表示层)+Spring(业务层)+Hibernate(持久层) SSH:Struts(表示层)+Spring(业务层)+Hibernate(持久层) Struts:Struts是一个表示 ...
- 《项目架构那点儿事》——Hibernate泛型Dao,让持久层简洁起来
[前言]hibernate作为持久层ORM技术,它对JDBC进行非常轻量级对象封装,使得我们可以随心所欲的使用面向对象的思想来操作数据 库.同时,作为后台开发的支撑,的确扮演了一个举足轻重的角色,那么 ...
- SSH三种框架及表示层、业务层和持久层的理解(转)
Struts(表示层)+Spring(业务层)+Hibernate(持久层) SSH:Struts(表示层)+Spring(业务层)+Hibernate(持久层) Struts:Struts是一个表示 ...
- 持久层框架JPA与Mybatis该如何选型
一.现状描述 目前java 持久层ORM框架应用最广泛的就是JPA和Mybatis.JPA只是一个ORM框架的规范, 对该规范的实现比较完整就是Spring Data JPA(底层基于Hibernat ...
- Mybatis详解系列(一)--持久层框架解决了什么及如何使用Mybatis
简介 Mybatis 是一个持久层框架,它对 JDBC 进行了高级封装,使我们的代码中不会出现任何的 JDBC 代码,另外,它还通过 xml 或注解的方式将 sql 从 DAO/Repository ...
随机推荐
- 设计模式--代理模式(C++版)
一:代理模式简介 专业版描述:为其他对象提供一种代理以控制对这个对象的访问. 在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用. 戏剧性描述: ...
- OpenCV探索之路(七):霍夫变换
我们如何在图像中快速识别出其中的圆和直线?一个非常有效的方法就是霍夫变换,它是图像中识别各种几何形状的基本算法之一. 霍夫线变换 霍夫线变换是一种在图像中寻找直线的方法.OpenCV中支持三种霍夫线变 ...
- ActionBar 通用方法
自定义actionBar布局:标题居中,左边有返回按键 <?xml version="1.0" encoding="utf-8"?> <Rel ...
- javaWeb学习总结(4)- HTML 关于head中的<meta>标签
关于<meta> 标签 <meta>标签出现在网页的标题部分,这些信息并不会出现在浏览器页面的显示之中,只会显示在源代码中.也就是在...当中. 主要用途是设置网页语言的编码方 ...
- (HTTPS)web 项目如何实现https
HTTPS实际是SSL over HTTP, 该协议通过SSL在发送方把原始数据进行加密,在接收方解密,因此,所传送的数据不容易被网络黑客截获和破解.本文介绍HTTPS的三种实现方法.方法一 静态超链 ...
- ElasticSearch的Marvel更新license
Marvel安装的时候需要申请一个license,否则只有30天的使用时间,到期后最多保存7天的监控数据,为了造成不必要的监控数据丢失,建议安装的同时注册一个lincense,方法如下: 1. ...
- 关于XAMPP环境配置
关于XAMPP软件 * Apache - 软件服务器(运行PHP) * 启动失败 * 原因 - 端口号被占用 * 错误信息 - Error: Apache shutdown unexpectedly ...
- 给Linux系统/网络管理员准备的Nmap命令的29个实用范例
我将用两个不同的部分来涵盖大部分NMAP的使用方法,这是nmap关键的第一部分.在下面的设置中,我使用两台已关闭防火墙的服务器来测试Nmap命令的工作情况. 192.168.0.100 – serve ...
- Qt自定义标签按钮
当你接触到Qt时,你会为它极为方便的跨平台方面感到吃惊,从而想尝试着使用Qt.渐渐地你会发现Qt自带的一些控件不能满足自己的需要,此时就需要我们自己定义一个属于自己的控件.总所周知,标签的风格设置类比 ...
- Bash的命令替换
命令替换:将命令替换为命令的输出,所有的shell支持使用反引号的方法进行命令替换.Bash支持两种形式:$(command) 和`command`命令替换是可以嵌套的,如果使用反引号的形式,在内部反 ...