SpringJdbc持久层封装,Spring jdbcTemplate封装,springJdbc泛型Dao,Spring baseDao封装

时间:2023-03-09 09:09:36
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,并没有深入再封装。

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

使用的一个例子:

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

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

©Copyright 蕃薯耀 2017年7月6日

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