• 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

    Java代码  收藏代码
    1. package com.lqy.spring.dao.impl;  
    2.   
    3. import java.io.Serializable;  
    4. import java.lang.reflect.Field;  
    5. import java.lang.reflect.Method;  
    6. import java.util.ArrayList;  
    7. import java.util.LinkedHashMap;  
    8. import java.util.List;  
    9. import java.util.Map;  
    10.   
    11. import org.springframework.beans.BeanWrapper;  
    12. import org.springframework.beans.factory.annotation.Autowired;  
    13. import org.springframework.jdbc.core.BeanPropertyRowMapper;  
    14. import org.springframework.jdbc.core.JdbcTemplate;  
    15.   
    16. import com.lqy.Utils.EntityUtils;  
    17. import com.lqy.Utils.StrUtils;  
    18. import com.lqy.spring.bean.Page;  
    19. import com.lqy.spring.dao.BaseDao;  
    20. import com.lqy.spring.editor.GenderEditor;  
    21. import com.lqy.spring.entity.SqlEntity;  
    22. import com.lqy.spring.enums.Gender;  
    23.   
    24. @SuppressWarnings({"unchecked","rawtypes"})  
    25. public class BaseDaoImpl<T> implements BaseDao<T> {  
    26.       
    27.       
    28.     @Autowired  
    29.     JdbcTemplate jdbcTemplate;  
    30.       
    31.     //entityClass.getSimpleName()=Person  
    32.     //entityClass.getName()=com.lqy.spring.c3p0.beans.Person  
    33.     protected Class<T> entityClass = (Class<T>) EntityUtils.getEntityClass(this.getClass());  
    34.   
    35.     //private  RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(entityClass);  
    36.       
    37.     private BeanPropertyRowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(entityClass){  
    38.         @Override  
    39.         protected void initBeanWrapper(BeanWrapper bw) {  
    40.             bw.registerCustomEditor(Gender.class, new GenderEditor());  
    41.             super.initBeanWrapper(bw);  
    42.         }  
    43.     };  
    44.       
    45.     /** 
    46.      * 获取实体 
    47.      * @param id 对象的id(Serializable) 
    48.      * @return T 对象 
    49.      * @author lqy 
    50.      * @since 2015-10-18 
    51.      */  
    52.     @Override  
    53.     public T get(Serializable id) {  
    54.         String sql = getSql() + "and id=? ";  
    55.         return (T)jdbcTemplate.queryForObject(sql, rowMapper, id);  
    56.     }  
    57.   
    58.     /** 
    59.      * 查询 
    60.      * @return List<T> 
    61.      * @author lqy 
    62.      * @since 2015-10-18 
    63.      */  
    64.     @Override  
    65.     public List<T> query() {  
    66.         return (List<T>) jdbcTemplate.query(getSql(), rowMapper);  
    67.     }  
    68.   
    69.     /** 
    70.      * 查询 
    71.      * @param page 分页参数 
    72.      * @param whereSql 查询条件(例:o.name=?) 
    73.      * @param params 查询条件对应的参数(List<Object>) 
    74.      * @return List<T> 
    75.      * @author lqy 
    76.      * @since 2015-10-18 
    77.      */  
    78.     @Override  
    79.     public List<T> query(Page page, String whereSql, List<Object> params) {  
    80.         List<Object> paramList = new ArrayList<Object>();  
    81.         if(!StrUtils.isEmpty(whereSql) && !StrUtils.isEmpty(params)){  
    82.             for (Object object : params) {  
    83.                 if(object instanceof Enum){  
    84.                     paramList.add(((Enum)object).ordinal());  
    85.                 }else{  
    86.                     paramList.add(object);  
    87.                 }  
    88.             }  
    89.         }  
    90.         String sql = getSql(page, whereSql, null);  
    91.         dealPage(page, sql, paramList);  
    92.           
    93.         if(!StrUtils.isEmpty(page)){  
    94.             paramList.add(page.getOffSize());  
    95.             paramList.add(page.getCurrentSize());  
    96.         }  
    97.         return (List<T>)jdbcTemplate.query(sql, rowMapper, paramList.toArray());  
    98.     }  
    99.   
    100.     /** 
    101.      * 查询 
    102.      * @param page 分页参数 
    103.      * @param orderby 排序条件(LinkedHashMap<String, String>) 
    104.      * @return List<T> 
    105.      * @author lqy 
    106.      * @since 2015-10-18 
    107.      */  
    108.     @Override  
    109.     public List<T> query(Page page, LinkedHashMap<String, String> orderby) {  
    110.         List<Object> paramsList = new ArrayList<Object>();  
    111.           
    112.         String sql = getSql(page, null, orderby);  
    113.         dealPage(page, sql, paramsList);  
    114.           
    115.         if(!StrUtils.isEmpty(page)){  
    116.             paramsList.add(page.getOffSize());  
    117.             paramsList.add(page.getCurrentSize());  
    118.         }  
    119.         return (List<T>)jdbcTemplate.query(sql, rowMapper, paramsList.toArray());  
    120.     }  
    121.   
    122.     /** 
    123.      * 查询 
    124.      * @param page 分页参数 
    125.      * @param whereSql 查询条件(例:o.name=?) 
    126.      * @param params 查询条件对应的参数(List<Object>) 
    127.      * @param orderby 排序条件(LinkedHashMap<String, String>) 
    128.      * @return List<T> 
    129.      * @author lqy 
    130.      * @since 2015-10-18 
    131.      */  
    132.     @Override  
    133.     public List<T> query(Page page, String whereSql, List<Object> params, LinkedHashMap<String, String> orderby) {  
    134.         List<Object> paramsList = new ArrayList<Object>();  
    135.         if(!StrUtils.isEmpty(whereSql) && !StrUtils.isEmpty(params)){  
    136.             for (Object object : params) {  
    137.                 if(object instanceof Enum){  
    138.                     paramsList.add(((Enum)object).ordinal());  
    139.                 }else{  
    140.                     paramsList.add(object);  
    141.                 }  
    142.             }  
    143.         }  
    144.           
    145.         String sql = getSql(page, whereSql, orderby);  
    146.         //System.out.println("sql ="+sql);  
    147.         dealPage(page, sql, paramsList);  
    148.           
    149.         if(!StrUtils.isEmpty(page)){  
    150.             paramsList.add(page.getOffSize());  
    151.             paramsList.add(page.getCurrentSize());  
    152.         }  
    153.           
    154.         return (List<T>)jdbcTemplate.query(sql, rowMapper, paramsList.toArray());  
    155.     }  
    156.   
    157.     /** 
    158.      * 更新 
    159.      * @param sql 自定义更新sql 
    160.      * @param params 查询条件对应的参数(List<Object>) 
    161.      * @return int 更新的数量 
    162.      * @author lqy 
    163.      * @since 2015-10-18 
    164.      */  
    165.     @Override  
    166.     public int update(String sql, List<Object> params) {  
    167.         //String sql="update person set name=? where id=?";  
    168.         return jdbcTemplate.update(sql, params.toArray());  
    169.     }  
    170.       
    171.     /** 
    172.      * 更新(先从数据库取出来再更新) 
    173.      * @param t 更新的对象 
    174.      * @return int 更新的数量 
    175.      * @author lqy 
    176.      * @since 2015-10-18 
    177.      */  
    178.     @Override  
    179.     public int update(T t) throws Exception{  
    180.         SqlEntity sqlEntity = getUpdateSql(t);  
    181.         //System.out.println("=====sqlEntity.getSql()="+sqlEntity.getSql());  
    182.         return jdbcTemplate.update(sqlEntity.getSql(), sqlEntity.getParams().toArray());  
    183.     }  
    184.       
    185.     /** 
    186.      * 更新(通过模板更新,把符合template条件的数据都更新为value对象中的值) 
    187.      * @param t 更新的对象 
    188.      * @return int 更新的数量 
    189.      * @author lqy 
    190.      * @since 2015-10-18 
    191.      */  
    192.     @Override  
    193.     public int update(T value,T template) throws Exception{  
    194.         SqlEntity sqlEntity = getUpdateSql(value,template);  
    195.         //System.out.println("=====update(T value,T template) sqlEntity.getSql()="+sqlEntity.getSql());  
    196.         return jdbcTemplate.update(sqlEntity.getSql(), sqlEntity.getParams().toArray());  
    197.     }  
    198.       
    199.     /** 
    200.      * 保存 
    201.      * @param t 保存的对象 
    202.      * @return int 保存的数量 
    203.      * @author lqy 
    204.      * @since 2015-10-18 
    205.      */  
    206.     @Override  
    207.     public int save(T t) throws Exception{  
    208.         SqlEntity sqlEntity = getSaveSql(t);  
    209.         return jdbcTemplate.update(sqlEntity.getSql(), sqlEntity.getParams().toArray());  
    210.     };  
    211.   
    212.     /** 
    213.      * 保存 
    214.      * @param sql 自定义保存sql 
    215.      * @param params 查询条件对应的参数(List<Object>) 
    216.      * @return int 保存的数量 
    217.      * @author lqy 
    218.      * @since 2015-10-18 
    219.      */  
    220.     @Override  
    221.     public int save(String sql, List<Object> params) {  
    222.         //String sql="INSERT INTO person (`name`,age,create_time) VALUES(?,?,?);";  
    223.         return jdbcTemplate.update(sql, params.toArray());  
    224.     }  
    225.   
    226.     /** 
    227.      * 删除 
    228.      * @param id 对象的id(Serializable) 
    229.      * @return int 删除的数量 
    230.      * @author lqy 
    231.      * @since 2015-10-18 
    232.      */  
    233.     @Override  
    234.     public int delete(Serializable id) {  
    235.         String sql="delete from " + StrUtils.changeName(this.entityClass.getSimpleName()) + " where id=?";  
    236.         return jdbcTemplate.update(sql, id);  
    237.     }  
    238.       
    239.     @SuppressWarnings("deprecation")  
    240.     @Override  
    241.     public int getCount(String whereSql, Object[] objects){  
    242.         String entityName = this.entityClass.getSimpleName();  
    243.         StringBuffer sql = new StringBuffer("select count(*) from ");  
    244.         sql.append(StrUtils.changeName(entityName));  
    245.         sql.append(" o ").append(whereSql);  
    246.         //System.out.println("getCount sql.toString()="+sql.toString());  
    247.         //return jdbcTemplate.queryForInt(sql.toString(), entityClass);  
    248.         return jdbcTemplate.queryForInt(sql.toString(), objects);  
    249.                   
    250.     }  
    251.       
    252.     protected String getSql(){  
    253.         String entityName = this.entityClass.getSimpleName();  
    254.         StringBuffer sql = new StringBuffer("select * from ");  
    255.         sql.append(StrUtils.changeName(entityName));  
    256.         sql.append(" o where 1=1 ");  
    257.         return sql.toString();  
    258.     }  
    259.       
    260.     protected String getSql(String whereSql){  
    261.         String entityName = this.entityClass.getSimpleName();  
    262.         StringBuffer sql = new StringBuffer("select * from ");  
    263.         sql.append(StrUtils.changeName(entityName));  
    264.         sql.append(" o where 1=1 ");  
    265.         if(!StrUtils.isEmpty(whereSql)){  
    266.             sql.append(" ").append(whereSql);  
    267.         }  
    268.         return sql.toString();  
    269.     }  
    270.       
    271.     /** 
    272.      * 获取sql 
    273.      * @param page 分页参数,如果为空,则不在sql增加limit ?,?  
    274.      * @param orderby 排序参数,如果为空,则不在sql增加ORDER BY 
    275.      * @param whereSql 查询条件参数,如果为空,则不在sql增加 and name=? 
    276.      * @return sql 
    277.      */  
    278.     protected String getSql(Page page, String whereSql, Map<String,String> orderby){  
    279.         String entityName = this.entityClass.getSimpleName();  
    280.         StringBuffer sql = new StringBuffer("select * from ");  
    281.         sql.append(StrUtils.changeName(entityName));  
    282.         sql.append(" o where 1=1 ");  
    283.         if(!StrUtils.isEmpty(whereSql)){  
    284.             sql.append(" ").append(whereSql);  
    285.         }  
    286.         if(!StrUtils.isEmpty(orderby)){  
    287.             sql.append(" ORDER BY ");  
    288.             for (String string : orderby.keySet()) {  
    289.                 String value = orderby.get(string);  
    290.                 if(StrUtils.isEmpty(value)){  
    291.                     value = "ASC";  
    292.                 }  
    293.                 sql.append("o.").append(string).append(" ").append(value.toUpperCase()).append(",");  
    294.             }  
    295.             if(sql.indexOf(",") > -1){  
    296.                 sql.deleteCharAt(sql.length()-1);  
    297.             }  
    298.         }  
    299.         if(!StrUtils.isEmpty(page)){  
    300.             sql.append(" limit ?,? ");  
    301.         }  
    302.         //System.out.println("------sql.toString()="+sql.toString());  
    303.         return sql.toString();  
    304.     }  
    305.       
    306.     private SqlEntity getUpdateSql(T t) throws Exception{  
    307.         SqlEntity sqlEntity = new SqlEntity();  
    308.         sqlEntity.setParams(new ArrayList<Object>());  
    309.         Field[] fields = entityClass.getDeclaredFields();  
    310.         StringBuffer sql = new StringBuffer("");  
    311.         sql.append("update ").append(StrUtils.changeName(entityClass.getSimpleName())).append(" o set ");  
    312.         for (Field field : fields) {  
    313.             StringBuffer methodName = new StringBuffer("");  
    314.             //System.out.println("===field.getType()="+field.getType());  
    315.             if(field.getType() == boolean.class){  
    316.                 if(field.getName().contains("is")){  
    317.                     methodName.append(field.getName());  
    318.                 }else{  
    319.                     methodName.append("is").append(StrUtils.firstCodeToUpperCase(field.getName()));  
    320.                 }  
    321.             }else{  
    322.                 methodName.append("get").append(StrUtils.firstCodeToUpperCase(field.getName()));  
    323.             }  
    324.             if(!"id".equals(field.getName())){  
    325.                 Method method = entityClass.getMethod(methodName.toString(), new Class[]{});  
    326.                 Object objectValue = method.invoke(t, new Object[]{});  
    327.                 if(objectValue instanceof Enum){  
    328.                     sqlEntity.getParams().add(((Enum)objectValue).ordinal());  
    329.                 }else{  
    330.                     sqlEntity.getParams().add(objectValue);  
    331.                 }  
    332.                 sql.append(" o.").append(StrUtils.changeName(field.getName())).append("= ?,");  
    333.             }  
    334.         }  
    335.         if(sql.indexOf(",") > -1){  
    336.             sql.deleteCharAt(sql.length() - 1);  
    337.         }  
    338.         sql.append(" where o.id=?");  
    339.         Method idMethod = entityClass.getMethod("getId", new Class[]{});  
    340.         sqlEntity.getParams().add(idMethod.invoke(t, new Object[]{}));  
    341.         sqlEntity.setSql(sql.toString());  
    342.         return sqlEntity;  
    343.     }  
    344.       
    345.     private SqlEntity getUpdateSql(T value, T template) throws Exception{  
    346.           
    347.         SqlEntity sqlEntity = new SqlEntity();  
    348.         sqlEntity.setParams(new ArrayList<Object>());  
    349.         Field[] fields = entityClass.getDeclaredFields();  
    350.         StringBuffer sql = new StringBuffer("");  
    351.         sql.append("update ").append(StrUtils.changeName(entityClass.getSimpleName())).append(" o set ");  
    352.         StringBuffer whereSql = new StringBuffer(" where ");  
    353.         for (Field field : fields) {  
    354.             StringBuffer methodName = new StringBuffer("");  
    355.             //System.out.println("===field.getType()="+field.getType());  
    356.             if(field.getType() == boolean.class){  
    357.                 if(field.getName().contains("is")){  
    358.                     methodName.append(field.getName());  
    359.                 }else{  
    360.                     methodName.append("is").append(StrUtils.firstCodeToUpperCase(field.getName()));  
    361.                 }  
    362.             }else{  
    363.                 methodName.append("get").append(StrUtils.firstCodeToUpperCase(field.getName()));  
    364.             }  
    365.             if(!"id".equals(field.getName())){  
    366.                 Method method = entityClass.getMethod(methodName.toString(), new Class[]{});  
    367.                 Object objectValue = method.invoke(value, new Object[]{});  
    368.                 if(!StrUtils.isEmpty(objectValue)){  
    369.                     if(objectValue instanceof Enum){  
    370.                         sqlEntity.getParams().add(((Enum)objectValue).ordinal());  
    371.                     }else{  
    372.                         sqlEntity.getParams().add(objectValue);  
    373.                     }  
    374.                     //sqlEntity.getParams().add(objectValue);  
    375.                     sql.append(" o.").append(StrUtils.changeName(field.getName())).append("= ?,");  
    376.                 }  
    377.             }  
    378.         }  
    379.           
    380.         for (Field field : fields) {  
    381.             StringBuffer methodName = new StringBuffer("");  
    382.             if(field.getType() == boolean.class){  
    383.                 if(field.getName().contains("is")){  
    384.                     methodName.append(field.getName());  
    385.                 }else{  
    386.                     methodName.append("is").append(StrUtils.firstCodeToUpperCase(field.getName()));  
    387.                 }  
    388.             }else{  
    389.                 methodName.append("get").append(StrUtils.firstCodeToUpperCase(field.getName()));  
    390.             }  
    391.             Method method = entityClass.getMethod(methodName.toString(), new Class[]{});  
    392.             Object objectValue = method.invoke(template, new Object[]{});  
    393.             if(!StrUtils.isEmpty(objectValue)){  
    394.                 sqlEntity.getParams().add(objectValue);  
    395.                 whereSql.append(" o.").append(StrUtils.changeName(field.getName())).append("= ? and");  
    396.             }  
    397.         }  
    398.         if(sql.indexOf(",") > -1){  
    399.             sql.deleteCharAt(sql.length() - 1);  
    400.         }  
    401.         if(whereSql.indexOf("and") > -1){  
    402.             sql.append(whereSql.substring(0, whereSql.length()-3));  
    403.             whereSql = new StringBuffer();  
    404.         }else{  
    405.             sql.append(whereSql);  
    406.         }  
    407.         sqlEntity.setSql(sql.toString());  
    408.         return sqlEntity;  
    409.     }  
    410.       
    411.     private SqlEntity getSaveSql(T t) throws Exception{  
    412.         SqlEntity sqlEntity = new SqlEntity();  
    413.         sqlEntity.setParams(new ArrayList<Object>());  
    414.         Field[] fields = entityClass.getDeclaredFields();  
    415.         StringBuffer sql = new StringBuffer("");  
    416.         sql.append("insert into ").append(StrUtils.changeName(entityClass.getSimpleName())).append(" ( ");  
    417.         int paramLength = 0;  
    418.         for (Field field : fields) {  
    419.             StringBuffer methodName = new StringBuffer("");  
    420.             if(field.getType() == boolean.class){  
    421.                 if(field.getName().contains("is")){  
    422.                     methodName.append(field.getName());  
    423.                 }else{  
    424.                     methodName.append("is").append(StrUtils.firstCodeToUpperCase(field.getName()));  
    425.                 }  
    426.             }else{  
    427.                 methodName.append("get").append(StrUtils.firstCodeToUpperCase(field.getName()));  
    428.             }  
    429.             Method method = entityClass.getMethod(methodName.toString(), new Class[]{});  
    430.             Object value = method.invoke(t, new Object[]{});  
    431.             if(!StrUtils.isEmpty(value)){  
    432.                 if(value instanceof Enum){  
    433.                     sqlEntity.getParams().add(((Enum) value).ordinal());  
    434.                 }else{  
    435.                     sqlEntity.getParams().add(value);  
    436.                 }  
    437.                 sql.append("`").append(StrUtils.changeName(field.getName())).append("`").append(",");  
    438.                 paramLength ++;  
    439.             }  
    440.         }  
    441.         if(sql.indexOf(",") > -1){  
    442.             sql.deleteCharAt(sql.length() - 1);  
    443.         }  
    444.         sql.append(") values(");  
    445.         for (int i=0;i<paramLength;i++) {  
    446.             sql.append("?,");  
    447.         }  
    448.         if(sql.indexOf(",") > -1){  
    449.             sql.deleteCharAt(sql.length() - 1);  
    450.         }  
    451.         sql.append(")");  
    452.         //System.out.println("sql.toString()="+sql.toString());  
    453.         sqlEntity.setSql(sql.toString());  
    454.         return sqlEntity;  
    455.     }  
    456.       
    457.     private void dealPage(Page page, String sql, List<Object> params){  
    458.         String whereSql = "";  
    459.         if(sql != null && !sql.trim().equals("")){  
    460.             int whereIndex = sql.toLowerCase().indexOf("where");  
    461.             int orderIndex = sql.toLowerCase().indexOf("order");  
    462.             int limitIndex = sql.toLowerCase().indexOf("limit");  
    463.             if(whereIndex > -1){  
    464.                 whereSql = sql.substring(whereIndex, sql.length());  
    465.                 orderIndex = whereSql.toLowerCase().indexOf("order");  
    466.             }  
    467.             if(whereIndex > -1 && orderIndex > -1){  
    468.                 whereSql = whereSql.substring(0, orderIndex - 1);  
    469.                 limitIndex = whereSql.toLowerCase().indexOf("limit");  
    470.             }  
    471.             if(whereIndex > -1 && limitIndex > -1){  
    472.                 whereSql = whereSql.substring(0, limitIndex - 1);  
    473.             }  
    474.         }  
    475.         if(page.getTotalSizeNew()){  
    476.             page.setTotalSize(getCount(whereSql, params.toArray()));  
    477.         }  
    478.         setPage(page);  
    479.     }  
    480.       
    481.     private void setPage(Page page){  
    482.         page.setTotalPages(page.getTotalSize()%page.getCurrentSize()==0?page.getTotalSize()/page.getCurrentSize():(page.getTotalSize()/page.getCurrentSize()+1));  
    483.         page.setCurrentPage(page.getOffSize()/page.getCurrentSize()+1);  
    484.     }  
    485. }  
    Java代码  收藏代码
    1. package com.lqy.spring.dao;  
    2.   
    3. import java.io.Serializable;  
    4. import java.util.LinkedHashMap;  
    5. import java.util.List;  
    6.   
    7. import com.lqy.spring.bean.Page;  
    8.   
    9.   
    10. public interface BaseDao<T> {  
    11.   
    12.     public T get(Serializable id);  
    13.       
    14.     public List<T> query();  
    15.       
    16.     public List<T> query(Page page, String whereSql, List<Object> params);  
    17.       
    18.     public List<T> query(Page page, LinkedHashMap<String, String> orderby);  
    19.       
    20.     public List<T> query(Page page, String whereSql, List<Object> params, LinkedHashMap<String, String> orderby);  
    21.       
    22.     public int update(String sql, List<Object> params);  
    23.       
    24.     public int update(T t) throws Exception;  
    25.       
    26.     public int update(T value,T template) throws Exception;  
    27.       
    28.     public int save(T t) throws Exception;  
    29.       
    30.     public int save(String sql, List<Object> params);  
    31.       
    32.     public int delete(Serializable id);  
    33.       
    34.     public int getCount(String whereSql, Object[] objects);  
    35. }  
    Java代码  收藏代码
    1. package com.lqy.spring.service.impl;  
    2.   
    3. import java.io.Serializable;  
    4. import java.util.LinkedHashMap;  
    5. import java.util.List;  
    6.   
    7. import org.springframework.beans.factory.annotation.Autowired;  
    8. import org.springframework.transaction.annotation.Isolation;  
    9. import org.springframework.transaction.annotation.Transactional;  
    10.   
    11. import com.lqy.spring.bean.Page;  
    12. import com.lqy.spring.dao.BaseDao;  
    13. import com.lqy.spring.service.BaseService;  
    14.   
    15. @Transactional  
    16. public class BaseServiceImpl<T> implements BaseService<T> {  
    17.   
    18.     @Autowired  
    19.     BaseDao<T> baseDao;  
    20.       
    21.     /** 
    22.      * 获取实体 
    23.      * @param id 对象的id(Serializable) 
    24.      * @return T 对象 
    25.      * @author lqy 
    26.      * @since 2015-10-18 
    27.      */  
    28.     @Transactional(isolation=Isolation.READ_COMMITTED,  
    29.             readOnly=true)  
    30.     @Override  
    31.     public T get(Serializable id) {  
    32.         return baseDao.get(id);  
    33.     }  
    34.   
    35.     /** 
    36.      * 查询 
    37.      * @return List<T> 
    38.      * @author lqy 
    39.      * @since 2015-10-18 
    40.      */  
    41.     @Transactional(isolation=Isolation.READ_COMMITTED,readOnly=true)  
    42.     @Override  
    43.     public List<T> query() {  
    44.         return baseDao.query();  
    45.     }  
    46.   
    47.     /** 
    48.      * 查询 
    49.      * @param page 分页参数 
    50.      * @param whereSql 查询条件(例:o.name=?) 
    51.      * @param params 查询条件对应的参数(List<Object>) 
    52.      * @return List<T> 
    53.      * @author lqy 
    54.      * @since 2015-10-18 
    55.      */  
    56.     @Transactional(isolation=Isolation.READ_COMMITTED,  
    57.             readOnly=true)  
    58.     @Override  
    59.     public List<T> query(Page page, String whereSql, List<Object> params) {  
    60.         return baseDao.query(page, whereSql, params);  
    61.     }  
    62.   
    63.     /** 
    64.      * 查询 
    65.      * @param page 分页参数 
    66.      * @param orderby 排序条件(LinkedHashMap<String, String>) 
    67.      * @return List<T> 
    68.      * @author lqy 
    69.      * @since 2015-10-18 
    70.      */  
    71.     @Transactional(isolation=Isolation.READ_COMMITTED,  
    72.             readOnly=true)  
    73.     @Override  
    74.     public List<T> query(Page page, LinkedHashMap<String, String> orderby) {  
    75.         return baseDao.query(page, orderby);  
    76.     }  
    77.   
    78.     /** 
    79.      * 查询 
    80.      * @param page 分页参数 
    81.      * @param whereSql 查询条件(例:o.name=?) 
    82.      * @param params 查询条件对应的参数(List<Object>) 
    83.      * @param orderby 排序条件(LinkedHashMap<String, String>) 
    84.      * @return List<T> 
    85.      * @author lqy 
    86.      * @since 2015-10-18 
    87.      */  
    88.     @Transactional(isolation=Isolation.READ_COMMITTED,  
    89.             readOnly=true)  
    90.     @Override  
    91.     public List<T> query(Page page, String whereSql, List<Object> params,  
    92.             LinkedHashMap<String, String> orderby) {  
    93.         return baseDao.query(page, whereSql, params, orderby);  
    94.     }  
    95.   
    96.     /** 
    97.      * 更新 
    98.      * @param sql 自定义更新sql 
    99.      * @param params 查询条件对应的参数(List<Object>) 
    100.      * @return int 更新的数量 
    101.      * @author lqy 
    102.      * @since 2015-10-18 
    103.      */  
    104.     @Override  
    105.     public int update(String sql, List<Object> params) {  
    106.         return baseDao.update(sql, params);  
    107.     }  
    108.   
    109.     /** 
    110.      * 更新(先从数据库取出来再更新) 
    111.      * @param t 更新的对象 
    112.      * @return int 更新的数量 
    113.      * @author lqy 
    114.      * @since 2015-10-18 
    115.      */  
    116.     @Override  
    117.     public int update(T t) throws Exception {  
    118.         return baseDao.update(t);  
    119.     }  
    120.       
    121.     /** 
    122.      * 更新(通过模板更新,把符合template条件的数据都更新为value对象中的值) 
    123.      * @param t 更新的对象 
    124.      * @return int 更新的数量 
    125.      * @author lqy 
    126.      * @since 2015-10-18 
    127.      */  
    128.     @Override  
    129.     public int update(T value,T template) throws Exception{  
    130.         return baseDao.update(value,template);  
    131.     }  
    132.   
    133.     /** 
    134.      * 保存 
    135.      * @param t 保存的对象 
    136.      * @return int 保存的数量 
    137.      * @author lqy 
    138.      * @since 2015-10-18 
    139.      */  
    140.     @Override  
    141.     public int save(T t) throws Exception {  
    142.         return baseDao.save(t);  
    143.     }  
    144.   
    145.     /** 
    146.      * 保存 
    147.      * @param sql 自定义保存sql 
    148.      * @param params 查询条件对应的参数(List<Object>) 
    149.      * @return int 保存的数量 
    150.      * @author lqy 
    151.      * @since 2015-10-18 
    152.      */  
    153.     @Override  
    154.     public int save(String sql, List<Object> params) {  
    155.         return baseDao.save(sql, params);  
    156.     }  
    157.   
    158.     /** 
    159.      * 删除 
    160.      * @param id 对象的id(Serializable) 
    161.      * @return int 删除的数量 
    162.      * @author lqy 
    163.      * @since 2015-10-18 
    164.      */  
    165.     @Override  
    166.     public int delete(Serializable id) {  
    167.         return baseDao.delete(id);  
    168.     }  
    169.   
    170. }  
    Java代码  收藏代码
    1. package com.lqy.spring.service;  
    2.   
    3. import java.io.Serializable;  
    4. import java.util.LinkedHashMap;  
    5. import java.util.List;  
    6.   
    7. import com.lqy.spring.bean.Page;  
    8.   
    9.   
    10. public interface BaseService<T> {  
    11.   
    12.     public T get(Serializable id);  
    13.       
    14.     public List<T> query();  
    15.       
    16.     public List<T> query(Page page, String whereSql, List<Object> params);  
    17.       
    18.     public List<T> query(Page page, LinkedHashMap<String, String> orderby);  
    19.       
    20.     public List<T> query(Page page, String whereSql, List<Object> params, LinkedHashMap<String, String> orderby);  
    21.       
    22.     public int update(String sql, List<Object> params);  
    23.       
    24.     public int update(T t) throws Exception;  
    25.       
    26.     public int update(T value,T template) throws Exception;  
    27.       
    28.     public int save(T t) throws Exception;  
    29.       
    30.     public int save(String sql, List<Object> params);  
    31.       
    32.     public int delete(Serializable id);  
    33. }  
    Java代码  收藏代码
    1. package com.lqy.spring.bean;  
    2.   
    3. public class Page {  
    4.   
    5.     private int currentSize;  
    6.     private int offSize;  
    7.     private int totalSize;  
    8.     private int totalPages;  
    9.     private int currentPage;  
    10.     private Boolean totalSizeNew;  
    11.       
    12.     /** 
    13.      * 分页构造函数 
    14.      * @author lqy 
    15.      * @since 2015-10-22 
    16.      */  
    17.     public Page() {  
    18.         super();  
    19.     }  
    20.       
    21.       
    22.     /** 
    23.      * 分页构造函数 
    24.      * @param currentSize 
    25.      * @param offSize 
    26.      * @author lqy 
    27.      * @since 2015-10-22 
    28.      */  
    29.     public Page(int currentSize, int offSize) {  
    30.         super();  
    31.         this.currentSize = currentSize;  
    32.         this.offSize = offSize;  
    33.     }  
    34.   
    35.     /** 
    36.      * 分页构造函数 
    37.      * @param currentSize 
    38.      * @param offSize 
    39.      * @param totalSizeNew 
    40.      * @author lqy 
    41.      * @since 2015-10-22 
    42.      */  
    43.     public Page(int currentSize, int offSize, boolean totalSizeNew) {  
    44.         super();  
    45.         this.currentSize = currentSize;  
    46.         this.offSize = offSize;  
    47.         this.totalSizeNew = totalSizeNew;  
    48.     }  
    49.   
    50.     /** 
    51.      * 分页构造函数 
    52.      * @param currentSize 
    53.      * @param offSize 
    54.      * @param totalSize 
    55.      * @param totalPages 
    56.      * @param currentPage 
    57.      * @param totalSizeNew 
    58.      * @author lqy 
    59.      * @since 2015-10-22 
    60.      */  
    61.     public Page(int currentSize, int offSize, int totalSize, int totalPages,  
    62.             int currentPage, boolean totalSizeNew) {  
    63.         super();  
    64.         this.currentSize = currentSize;  
    65.         this.offSize = offSize;  
    66.         this.totalSize = totalSize;  
    67.         this.totalPages = totalPages;  
    68.         this.currentPage = currentPage;  
    69.         this.totalSizeNew = totalSizeNew;  
    70.     }  
    71.   
    72.     public int getCurrentSize() {  
    73.         return currentSize;  
    74.     }  
    75.   
    76.     public void setCurrentSize(int currentSize) {  
    77.         this.currentSize = currentSize;  
    78.     }  
    79.   
    80.     public int getOffSize() {  
    81.         return offSize;  
    82.     }  
    83.   
    84.     public void setOffSize(int offSize) {  
    85.         this.offSize = offSize;  
    86.     }  
    87.   
    88.     public int getTotalSize() {  
    89.         return totalSize;  
    90.     }  
    91.   
    92.     public void setTotalSize(int totalSize) {  
    93.         this.totalSize = totalSize;  
    94.     }  
    95.   
    96.     public int getTotalPages() {  
    97.         return totalPages;  
    98.     }  
    99.   
    100.     public void setTotalPages(int totalPages) {  
    101.         this.totalPages = totalPages;  
    102.     }  
    103.   
    104.     public int getCurrentPage() {  
    105.         return currentPage;  
    106.     }  
    107.   
    108.     public void setCurrentPage(int currentPage) {  
    109.         this.currentPage = currentPage;  
    110.     }  
    111.   
    112.     public Boolean getTotalSizeNew() {  
    113.         return totalSizeNew;  
    114.     }  
    115.   
    116.     public void setTotalSizeNew(Boolean totalSizeNew) {  
    117.         this.totalSizeNew = totalSizeNew;  
    118.     }  
    119.   
    120.     @Override  
    121.     public String toString() {  
    122.         return "Page [currentSize=" + currentSize + ", offSize=" + offSize  
    123.                 + ", totalSize=" + totalSize + ", totalPages=" + totalPages  
    124.                 + ", currentPage=" + currentPage + ", totalSizeNew="  
    125.                 + totalSizeNew + "]";  
    126.     }  
    127.   
    128.       
    129.       
    130.       
    131.       
    132. }  

    使用的一个例子:

    Java代码  收藏代码
    1. package com.lqy.spring.service.impl;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.LinkedHashMap;  
    5. import java.util.List;  
    6.   
    7. import org.springframework.beans.factory.annotation.Autowired;  
    8. import org.springframework.stereotype.Service;  
    9. import org.springframework.transaction.annotation.Transactional;  
    10.   
    11. import com.lqy.Utils.StrUtils;  
    12. import com.lqy.exception.PersonMoneyNotEnoughException;  
    13. import com.lqy.spring.bean.Page;  
    14. import com.lqy.spring.bean.Person;  
    15. import com.lqy.spring.dao.PersonDao;  
    16. import com.lqy.spring.service.BookService;  
    17. import com.lqy.spring.service.PersonService;  
    18.   
    19.   
    20. @Service  
    21. public class PersonServiceImpl extends BaseServiceImpl<Person> implements PersonService {  
    22.       
    23.     @Autowired  
    24.     PersonDao personDao;  
    25.     @Autowired  
    26.     BookService bookService;  
    27.       
    28.     @Override  
    29.     public List<Person> getPersons(Page page, String name, Integer age, Integer statusType){  
    30.         StringBuffer whereSql = new StringBuffer();  
    31.         List<Object> params = new ArrayList<Object>();  
    32.         LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();  
    33.           
    34.         if(!StrUtils.isEmpty(name)){  
    35.             whereSql.append(" and o.name like ?");  
    36.             params.add("%"+name+"%");  
    37.         }  
    38.         if(!StrUtils.isEmpty(age)){  
    39.             whereSql.append(" and o.age = ?");  
    40.             params.add(age);  
    41.         }  
    42.         if(!StrUtils.isEmpty(statusType)){  
    43.             whereSql.append(" and o.statusType = ?");  
    44.             params.add(statusType);  
    45.         }  
    46.         orderby.put("create_time", "desc");  
    47.         orderby.put("id", "desc");  
    48.           
    49.         return personDao.query(page, whereSql.toString(), params, orderby);  
    50.     }  
    51.       
    52.     @Transactional  
    53.     public int buyBook(Integer personId, Double price) throws Exception{  
    54.         int result = -1;  
    55.         Person person = personDao.get(personId);  
    56.         if(!StrUtils.isEmpty(person)){  
    57.             Double leftMoney = person.getMoney() - price;  
    58.             if(leftMoney >= 0){  
    59.                 person.setMoney(leftMoney);  
    60.                 result = personDao.update(person);  
    61.             }else{  
    62.                 throw new PersonMoneyNotEnoughException();  
    63.             }  
    64.         }  
    65.         return result;  
    66.     }  
    67.       
    68.     @Transactional  
    69.     @Override  
    70.     public int buyBook(Integer personId, Integer bookId, Integer amount) throws Exception{  
    71.         int result = -1;  
    72.         Person person = personDao.get(personId);  
    73.         if(!StrUtils.isEmpty(person)){  
    74.             Double price = bookService.getBooksPrices(bookId, amount);  
    75.             Double leftMoney = person.getMoney() - price;  
    76.             if(leftMoney >= 0){  
    77.                 person.setMoney(leftMoney);  
    78.                 personDao.update(person);  
    79.                 bookService.sellBooks(bookId, amount);  
    80.                 result = 1;  
    81.             }else{  
    82.                 throw new PersonMoneyNotEnoughException();  
    83.             }  
    84.         }  
    85.         return result;  
    86.     }  
    87.       
    88. }  

    (如果你觉得文章对你有帮助,欢迎捐赠,^_^,谢谢!) 

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    ©Copyright 蕃薯耀 2017年7月6日

    http://www.cnblogs.com/fanshuyao/

  • 相关阅读:
    数据库操作语句大全(sql)
    尚未在 Web 服务器上注册ASP.NET 4.5。安装VS15后的问题(转)
    ASP.NET通过http/https的POST方式,发送和接受XML文件内容(转)
    C# 的关键字详细介绍(转)
    12个css高级技巧.html
    CentOS上安装elasticsearch
    springboot例子
    ajax的XmlHttpRequest对象常用方法
    阿里云oss操作
    Python出现Could not find a version that satisfies the requirement openpyxl (from versions: )
  • 原文地址:https://www.cnblogs.com/fanshuyao/p/7127265.html
Copyright © 2020-2023  润新知