SpringJdbc持久层封装,Spring jdbcTemplate封装,springJdbc泛型Dao,Spring baseDao封装
Posted 蕃薯耀
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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,并没有深入再封装。
封装基于Spring4+Mysql
- 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()+
以上是关于SpringJdbc持久层封装,Spring jdbcTemplate封装,springJdbc泛型Dao,Spring baseDao封装的主要内容,如果未能解决你的问题,请参考以下文章