DAOServiceImpl.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /*
  2. * Copyright 2009 by primedata Corporation.
  3. * ,
  4. *
  5. * All rights reserved.
  6. *
  7. * This software is the confidential and proprietary information of
  8. * primedata Corporation ("Confidential Information"). You
  9. * shall not disclose such Confidential Information and shall use
  10. * it only in accordance with the terms of the license agreement
  11. * you entered into with primedata.
  12. */
  13. package com.primeton.dams.utils.template.impl;
  14. import com.primeton.dams.utils.template.CoreSQLParser;
  15. import com.primeton.dams.utils.template.DOResultTransformer;
  16. import com.primeton.dams.utils.template.HibernateStatementSessionFactoryBean;
  17. import com.primeton.dams.utils.template.IDAOService;
  18. import com.primeton.dams.utils.template.Page;
  19. import lombok.NonNull;
  20. import lombok.extern.slf4j.Slf4j;
  21. import org.apache.commons.lang.StringUtils;
  22. import org.hibernate.SQLQuery;
  23. import org.hibernate.internal.QueryImpl;
  24. import org.hibernate.transform.ResultTransformer;
  25. import org.hibernate.transform.Transformers;
  26. import org.slf4j.Logger;
  27. import org.slf4j.LoggerFactory;
  28. import org.springframework.beans.factory.annotation.Autowired;
  29. import org.springframework.dao.DataAccessException;
  30. import org.springframework.jdbc.core.JdbcTemplate;
  31. import org.springframework.stereotype.Repository;
  32. import javax.persistence.EntityManager;
  33. import javax.persistence.LockModeType;
  34. import javax.persistence.NoResultException;
  35. import javax.persistence.NonUniqueResultException;
  36. import javax.persistence.PersistenceContext;
  37. import javax.persistence.Query;
  38. import java.io.Serializable;
  39. import java.util.ArrayList;
  40. import java.util.Collection;
  41. import java.util.HashMap;
  42. import java.util.Iterator;
  43. import java.util.List;
  44. import java.util.Map;
  45. /**
  46. * find开头的方法是HQL方法,query开头的是SQL方法。
  47. * @author user
  48. * @version 1.0 2007-1-27
  49. *
  50. * @author zhaopx
  51. * @version 7.1
  52. * @date 2020-08-25
  53. */
  54. @Slf4j
  55. @Repository(value = "daoService")
  56. public class DAOServiceImpl implements IDAOService {
  57. /**
  58. * LOG
  59. */
  60. private static Logger logger = LoggerFactory.getLogger(DAOServiceImpl.class);
  61. @Autowired
  62. JdbcTemplate jdbcTemplate;
  63. @PersistenceContext
  64. EntityManager entityManager;
  65. @Override
  66. public JdbcTemplate getJdbcTemplate() {
  67. return jdbcTemplate;
  68. }
  69. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  70. this.jdbcTemplate = jdbcTemplate;
  71. }
  72. public DAOServiceImpl() {
  73. super();
  74. }
  75. /** Get HQL from xxxSql.xml file*/
  76. @Override
  77. public String getSQL(String name) {
  78. return HibernateStatementSessionFactoryBean.getStatementText(name);
  79. }
  80. /** Get dynamic HQL from xxxSql.xml file, voOrMap is a VO or a map.*/
  81. @Override
  82. public String getSQL(String name, Object voOrMap) {
  83. return HibernateStatementSessionFactoryBean.getStatementText(name, voOrMap);
  84. }
  85. /** Get dynamic Params from xxxSql.xml file, voOrMap is a VO or a map.*/
  86. @Override
  87. public Object[] getParam(String name, Object voOrMap) {
  88. return HibernateStatementSessionFactoryBean.getStatementParam(name, voOrMap);
  89. }
  90. /** Get dynamic Params from xxxSql.xml file, voOrMap is a VO or a map.*/
  91. @Override
  92. public Map getMapParam(String name, Object voOrMap) {
  93. return HibernateStatementSessionFactoryBean.getStatementParamMap(name, voOrMap);
  94. }
  95. //Persist the given transient instance
  96. @Override
  97. public void add(Object vo) throws DataAccessException {
  98. entityManager.persist(vo);
  99. }
  100. //Update the given persistent instance
  101. @Override
  102. public void update(Object vo) throws DataAccessException {
  103. entityManager.merge(vo);
  104. }
  105. @Override
  106. public void merge(Object entity) throws DataAccessException {
  107. entityManager.merge(entity);
  108. }
  109. //Save or update the given persistent instance, according to its id
  110. @Override
  111. public void addOrUpdate(Object vo) throws DataAccessException {
  112. entityManager.persist(vo);
  113. }
  114. @Override
  115. public void addAll(Collection vos) throws DataAccessException {
  116. for (Object vo : vos) {
  117. entityManager.persist(vo);
  118. }
  119. }
  120. //Return the persistent instance of the given entity class with the given identifier,
  121. //or null if not found
  122. @Override
  123. public Object get(Class entityClass, Serializable id) {
  124. return entityManager.find(entityClass, id);
  125. }
  126. //Return the persistent instance of the given entity class with the given identifier,
  127. //or null if not found
  128. @Override
  129. public Object get(Class entityClass, Serializable id, LockModeType lockMode) {
  130. return entityManager.find(entityClass, id, lockMode);
  131. }
  132. //Delete the given persistent instance, according to its id
  133. @Override
  134. public void delete(Class entityClass, Serializable id) throws DataAccessException {
  135. entityManager.remove(get(entityClass, id));
  136. }
  137. //Delete the given persistent instance
  138. @Override
  139. public void delete(Object entity) throws DataAccessException {
  140. entityManager.remove(entity);
  141. }
  142. //Delete all given persistent instances
  143. @Override
  144. public void deleteAll(Collection entities) throws DataAccessException {
  145. for (Object entity : entities) {
  146. entityManager.remove(entity);
  147. }
  148. }
  149. //Update/delete all objects according to the given query
  150. @Override
  151. public int execute(String updateSql) {
  152. return entityManager.createNativeQuery(updateSql).executeUpdate();
  153. }
  154. //Update/delete all objects according to the given query
  155. @Override
  156. public int execute(String updateSql, Object[] params) {
  157. final javax.persistence.Query nativeQuery = entityManager.createNativeQuery(updateSql);
  158. for (int i=1; params!=null && i<params.length+1; i++) {
  159. nativeQuery.setParameter(i, params[i-1]);
  160. }
  161. return nativeQuery.executeUpdate();
  162. }
  163. //flush session
  164. @Override
  165. public void flush() {
  166. entityManager.flush();
  167. }
  168. //clear session
  169. @Override
  170. public void clear() {
  171. entityManager.clear();
  172. }
  173. // count(*).
  174. @Override
  175. public int count(String queryString, Object[] values) {
  176. return countSQL(queryString, values);
  177. }
  178. /**
  179. * 执行SQL查询。提供结果集的转换接口ResultTransformer。
  180. * @param query
  181. * @param params
  182. * @param rt
  183. * @param firstResult
  184. * @param maxResult
  185. * @return
  186. */
  187. @Override
  188. public List query(javax.persistence.Query query, Object[] params, ResultTransformer rt, final int firstResult, final int maxResult) {
  189. for (int i=1; params!=null && i<params.length+1; i++) {
  190. query.setParameter(i, params[i-1]);
  191. }
  192. query.setMaxResults(maxResult);
  193. query.setFirstResult(firstResult);
  194. if (rt == null) {
  195. query.unwrap(org.hibernate.SQLQuery.class)
  196. .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  197. } else {
  198. query.unwrap(org.hibernate.SQLQuery.class)
  199. .setResultTransformer(rt);
  200. }
  201. return query.getResultList();
  202. }
  203. @Override
  204. public List query(javax.persistence.Query query, Object[] params, ResultTransformer rt) {
  205. for (int i=1; params!=null && i<params.length+1; i++) {
  206. query.setParameter(i, params[i-1]);
  207. }
  208. if (rt == null) {
  209. query.unwrap(org.hibernate.SQLQuery.class)
  210. .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  211. } else {
  212. query.unwrap(org.hibernate.SQLQuery.class)
  213. .setResultTransformer(rt);
  214. }
  215. return query.getResultList();
  216. }
  217. @Override
  218. public List query(String sql, Object[] params, ResultTransformer rt) {
  219. return query(entityManager.createNativeQuery(sql), params, rt);
  220. }
  221. /**
  222. * 执行SQL查询
  223. * @param id 脚本
  224. * @param params 参数
  225. * @param entityClass 转换
  226. * @return Object[]/Object
  227. */
  228. @Override
  229. public List queryById(String id, Map<String, Object> params, Class entityClass) {
  230. final String sql = getSQL(id, params);
  231. if(StringUtils.isBlank(sql)) {
  232. throw new IllegalArgumentException("undefined statement id: " + id);
  233. }
  234. final Object[] sqlParams = (params == null ? null : getParam(id, params));
  235. final Query nativeQuery = entityManager.createNativeQuery(sql);
  236. if (entityClass == null) {
  237. nativeQuery.unwrap(org.hibernate.SQLQuery.class)
  238. .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  239. } else {
  240. nativeQuery.unwrap(org.hibernate.SQLQuery.class)
  241. .setResultTransformer(new DOResultTransformer(entityClass));
  242. }
  243. return query(nativeQuery, sqlParams, entityClass, null, null);
  244. }
  245. /**
  246. * 执行 statement id 的查询,返回 ResultTransformer 的转换结果, 并应用分页
  247. * @param id
  248. * @param params
  249. * @param entityClass
  250. * @param firstResult
  251. * @param maxResult
  252. * @return
  253. */
  254. @Override
  255. public List queryById(String id, Map<String, Object> params, Class entityClass, final int firstResult, final int maxResult) {
  256. final String sql = getSQL(id, params);
  257. if(StringUtils.isBlank(sql)) {
  258. throw new IllegalArgumentException("undefined statement id: " + id);
  259. }
  260. final Object[] sqlParams = (params == null ? null : getParam(id, params));
  261. final Query nativeQuery = entityManager.createNativeQuery(sql);
  262. if (entityClass == null) {
  263. nativeQuery.unwrap(org.hibernate.SQLQuery.class)
  264. .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  265. } else {
  266. nativeQuery.unwrap(org.hibernate.SQLQuery.class)
  267. .setResultTransformer(new DOResultTransformer(entityClass));
  268. }
  269. return query(nativeQuery, sqlParams, entityClass, firstResult, maxResult);
  270. }
  271. private List query(javax.persistence.Query query, Object[] params, Class entityClass, final Integer firstResult, final Integer maxResult) {
  272. for (int i=1; params!=null && i<params.length+1; i++) {
  273. query.setParameter(i, params[i-1]);
  274. }
  275. if (firstResult != null) {
  276. query.setFirstResult(firstResult);
  277. }
  278. if (maxResult != null) {
  279. query.setMaxResults(maxResult);
  280. }
  281. return query.getResultList();
  282. }
  283. @Override
  284. public List querySQL(javax.persistence.Query query, Object[] params) {
  285. return this.query(query, params, null);
  286. }
  287. @Override
  288. public List queryForMap(String sql, Object[] params) {
  289. return this.query(sql, params, Transformers.ALIAS_TO_ENTITY_MAP);
  290. }
  291. @Override
  292. public List queryForMap(javax.persistence.Query query, Object[] params) {
  293. return this.query(query, params, Transformers.ALIAS_TO_ENTITY_MAP);
  294. }
  295. @Override
  296. public List queryForMap(String sql, Object[] params, int firstResult, int maxResult) {
  297. final javax.persistence.Query query1 = entityManager.createNativeQuery(sql);
  298. for (int i=1; params!=null && i<params.length+1; i++) {
  299. query1.setParameter(i, params[i-1]);
  300. }
  301. query1.setFirstResult(firstResult);
  302. query1.setMaxResults(maxResult);
  303. query1.unwrap(org.hibernate.SQLQuery.class)
  304. .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  305. return query1.getResultList();
  306. }
  307. private List queryForEntity(javax.persistence.Query query, Object[] params, Class entityClass) {
  308. for (int i=1; params!=null && i<params.length+1; i++) {
  309. query.setParameter(i, params[i-1]);
  310. }
  311. return query.getResultList();
  312. }
  313. @Override
  314. public List queryForEntity(String sql, Class entityClass) {
  315. final javax.persistence.Query query1 = entityManager.createQuery(sql, entityClass);
  316. query1.unwrap(QueryImpl.class)
  317. .setResultTransformer(new DOResultTransformer(entityClass));
  318. return query1.getResultList();
  319. }
  320. @Override
  321. public List queryForEntity(String sql, Object[] params, Class entityClass) {
  322. final javax.persistence.Query query1 = entityManager.createQuery(sql);
  323. query1.unwrap(QueryImpl.class)
  324. .setResultTransformer(new DOResultTransformer(entityClass));
  325. return this.queryForEntity(query1, params, entityClass);
  326. }
  327. @Override
  328. public List queryForEntity(String sql, Object[] params,
  329. Class entityClass, int firstResult, int maxResult) {
  330. final javax.persistence.Query query1 = entityManager.createQuery(sql);
  331. QueryImpl query = query1.unwrap(QueryImpl.class);
  332. query.setResultTransformer(new DOResultTransformer(entityClass));
  333. query.setMaxResults(maxResult).setFirstResult(firstResult);
  334. return this.queryForEntity(query1, params, entityClass);
  335. }
  336. /**
  337. * 查询返回一条数据,无数据则返回 null
  338. * @param sql
  339. * @param params
  340. * @param entityClass
  341. * @param <T>
  342. * @return
  343. */
  344. public <T> T queryForObject(String sql, Object[] params, @NonNull Class<T> entityClass) {
  345. final javax.persistence.Query query1 = entityManager.createNativeQuery(sql);
  346. for (int i=1; params!=null && i<params.length+1; i++) {
  347. query1.setParameter(i, params[i-1]);
  348. }
  349. query1.unwrap(org.hibernate.SQLQuery.class)
  350. .setResultTransformer(new DOResultTransformer(entityClass));
  351. try {
  352. return (T) query1.getSingleResult();
  353. } catch (NoResultException e) {
  354. // 未查询到数据,则返回 null
  355. return null;
  356. } catch (NonUniqueResultException e) {
  357. // 查询到多条,则返回第 0 条
  358. return (T)query1.getResultList().get(0);
  359. }
  360. }
  361. @Override
  362. public long queryForLong(String sql, Object[] params) {
  363. return countSQL(sql, params);
  364. }
  365. @Override
  366. public int updateById(String id, Map<String, Object> params) {
  367. final String sql = getSQL(id, params);
  368. if(StringUtils.isBlank(sql)) {
  369. throw new IllegalArgumentException("undefined statement id: " + id);
  370. }
  371. final Object[] sqlParams = (params == null ? null : getParam(id, params));
  372. SQLQuery query = entityManager.createNativeQuery(sql).unwrap(SQLQuery.class);
  373. if (sqlParams != null && sqlParams.length > 0) {
  374. for (int i=1; i<sqlParams.length+1; i++) {
  375. query.setParameter(i, sqlParams[i-1]);
  376. }
  377. }
  378. return query.executeUpdate();
  379. }
  380. @Override
  381. public int updateSQL(String sql, final Object[] params) {
  382. if (StringUtils.isBlank(sql)) {
  383. return 0;
  384. }
  385. SQLQuery query = entityManager.createNativeQuery(sql).unwrap(SQLQuery.class);
  386. if (params != null && params.length > 0) {
  387. for (int i=1; i<params.length+1; i++) {
  388. query.setParameter(i, params[i-1]);
  389. }
  390. }
  391. return query.executeUpdate();
  392. }
  393. @Override
  394. public int[] batchUpdateSQL(String[] sql) {
  395. int[] r = new int[sql.length];
  396. for (int i = 0; i < sql.length; i++) {
  397. r[i] = updateSQL(sql[i], null);
  398. }
  399. return r;
  400. }
  401. @Override
  402. public List queryPageList(String sql, Object[] params, Page page) {
  403. SQLQuery query = entityManager.createNativeQuery(sql).unwrap(SQLQuery.class);
  404. for (int i=1; params!=null && i<params.length+1; i++) {
  405. query.setParameter(i, params[i-1]);
  406. }
  407. int totalCount = this.countSQL(sql, params);
  408. query.setMaxResults(page.getPageSize());
  409. query.setFirstResult(page.getStartIndex());
  410. List list = new ArrayList();
  411. if (totalCount > 0) {
  412. list = query.list();
  413. }
  414. page.setCurrRecords(list.size());
  415. page.setQueryResult(list);
  416. page.setTotalRecs(totalCount);
  417. return list;
  418. }
  419. @Override
  420. public List queryPageMap(String sql, Object[] params, Page page) {
  421. int totalCount = this.countSQL(sql, params);
  422. List<?> list = new ArrayList();
  423. if (totalCount > 0) {
  424. final javax.persistence.Query nativeQuery = entityManager.createNativeQuery(sql);
  425. SQLQuery query = nativeQuery.unwrap(SQLQuery.class);
  426. query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  427. query.setMaxResults(page.getPageSize());
  428. query.setFirstResult(page.getStartIndex());
  429. return this.queryForMap(nativeQuery, params);
  430. }
  431. page.setCurrRecords(list.size());
  432. page.setQueryResult(list);
  433. page.setTotalRecs(totalCount);
  434. return list;
  435. }
  436. /*
  437. * (non-Javadoc)
  438. * @see com.primedata.primedatamm.core.dao.IDAOService
  439. * #queryPageEntity(java.lang.String, java.lang.Object[],
  440. * com.primedata.primedatamm.core.common.Page, EntityList)
  441. */
  442. @Override
  443. public List queryPageEntity(String sql, Object[] params, Page page, @NonNull Class entityClass) {
  444. int totalCount = this.countSQL(sql, params);
  445. List<?> list = new ArrayList();
  446. if (totalCount > 0) {
  447. final javax.persistence.Query nativeQuery = entityManager.createNativeQuery(sql);
  448. SQLQuery query = nativeQuery.unwrap(SQLQuery.class);
  449. for (int i=1; params!=null && i<params.length+1; i++) {
  450. query.setParameter(i, params[i-1]);
  451. }
  452. nativeQuery.unwrap(org.hibernate.SQLQuery.class)
  453. .setResultTransformer(new DOResultTransformer(entityClass));
  454. query.setMaxResults(page.getPageSize());
  455. query.setFirstResult(page.getStartIndex());
  456. return query.list();
  457. }
  458. page.setCurrRecords(list.size());
  459. page.setQueryResult(list);
  460. page.setTotalRecs(totalCount);
  461. return list;
  462. }
  463. /*
  464. * (non-Javadoc)
  465. * @see com.primedata.primedatamm.core.dao.IDAOService#getCountSQL(java.lang.String)
  466. */
  467. @Override
  468. public String getCountSQL(String sql) {
  469. return CoreSQLParser.getCountSQL(sql);
  470. }
  471. // count sql query result.
  472. @Override
  473. public int countSQL(String sql, Object[] params) {
  474. String strQuery = this.getCountSQL(sql);
  475. int count = 0;
  476. final javax.persistence.Query nativeQuery = entityManager.createNativeQuery(strQuery);
  477. for (int i=1; params!=null && i<params.length+1; i++) {
  478. nativeQuery.setParameter(i, params[i-1]);
  479. }
  480. if (nativeQuery != null) {
  481. // 取出count总数
  482. final Object singleResult = nativeQuery.getSingleResult();
  483. if(singleResult instanceof Number) {
  484. count = ((Number)singleResult).intValue();
  485. }
  486. }
  487. return count;
  488. }
  489. // 创建statement的id=getSEQ_xxx,其SQL如: select $sequence$.nextval from dual
  490. @Override
  491. public Long getSQNextValue(String sequence) {
  492. Map<String,Object> map = new HashMap<String,Object>();
  493. map.put("sequence", sequence);
  494. return queryForLong(getSQL("getSQNextValue", map), getParam("getSQNextValue", map));
  495. }
  496. @Override
  497. public Long getSQCurrValue(String sequence) {
  498. Map<String,Object> map = new HashMap<String,Object>();
  499. map.put("sequence", sequence);
  500. return queryForLong(getSQL("getSQCurrValue", map), getParam("getSQCurrValue", map));
  501. }
  502. }