BaseJpaService.java 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package com.yihu.ehr.query;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.yihu.ehr.constants.PageArg;
  4. import com.yihu.ehr.lang.SpringContext;
  5. import org.apache.commons.lang3.StringUtils;
  6. import org.hibernate.Query;
  7. import org.hibernate.Session;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.data.domain.Sort;
  10. import org.springframework.data.jpa.repository.JpaRepository;
  11. import org.springframework.data.repository.PagingAndSortingRepository;
  12. import org.springframework.jdbc.core.JdbcTemplate;
  13. import org.springframework.transaction.annotation.Propagation;
  14. import org.springframework.transaction.annotation.Transactional;
  15. import javax.persistence.EntityManager;
  16. import javax.persistence.PersistenceContext;
  17. import javax.persistence.criteria.CriteriaBuilder;
  18. import javax.persistence.criteria.CriteriaQuery;
  19. import javax.persistence.criteria.Predicate;
  20. import javax.persistence.criteria.Root;
  21. import javax.persistence.metamodel.EntityType;
  22. import java.io.Serializable;
  23. import java.lang.reflect.ParameterizedType;
  24. import java.lang.reflect.Type;
  25. import java.text.ParseException;
  26. import java.util.ArrayList;
  27. import java.util.Arrays;
  28. import java.util.List;
  29. import java.util.UUID;
  30. /**
  31. * Service基础类。此类基于Spring Data JPA进行封装(Spring Data JPA又是基于JPA封装,EHR平台使用Hibernate作为JPA实现者)。
  32. * 需要注意的是,部分功能会跳过JPA接口而直接使用Hibernate接口,比如访问Hibernate的Session接口,因为它把JPA的EntityManager功能强大。
  33. *
  34. * @author lincl
  35. * @author Sand
  36. * @version 1.0
  37. * @created 2016.2.3。
  38. */
  39. @Transactional(propagation = Propagation.SUPPORTS)
  40. public class BaseJpaService<T, R> {
  41. @PersistenceContext
  42. protected EntityManager entityManager;
  43. @Autowired
  44. protected JdbcTemplate jdbcTemplate;
  45. @Autowired
  46. protected ObjectMapper objectMapper;
  47. Class<R> repoClass;
  48. public BaseJpaService() {
  49. Type genType = getClass().getGenericSuperclass();
  50. if ((genType instanceof ParameterizedType)) {
  51. Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
  52. if (params.length == 2) {
  53. repoClass = (Class) params[1];
  54. }
  55. }
  56. }
  57. public T save(T entity) {
  58. return (T) getRepository().save(entity);
  59. }
  60. public T retrieve(Serializable id) {
  61. return (T) getRepository().findOne(id);
  62. }
  63. public void delete(Serializable id) {
  64. getRepository().delete(id);
  65. }
  66. public void delete(T entity) {
  67. getRepository().delete(entity);
  68. }
  69. public void delete(Iterable ids) {
  70. Iterable list = getRepository().findAll(ids);
  71. getRepository().delete(list);
  72. }
  73. public Class<T> getEntityClass() {
  74. Type genType = this.getClass().getGenericSuperclass();
  75. Type[] parameters = ((ParameterizedType) genType).getActualTypeArguments();
  76. return (Class) parameters[0];
  77. }
  78. public List<T> search(String fields, String filters, String sorts, Integer page, Integer size) throws ParseException {
  79. URLQueryParser queryParser = createQueryParser(fields, filters, sorts);
  80. CriteriaQuery query = queryParser.makeCriteriaQuery();
  81. if (page == null || page <= 0) {
  82. page = PageArg.DefaultPage;
  83. }
  84. if (size == null || size <= 0 || size > 10000) {
  85. size = PageArg.DefaultSize;
  86. }
  87. List resultList = entityManager
  88. .createQuery(query)
  89. .setFirstResult((page - 1) * size)
  90. .setMaxResults(size)
  91. .getResultList();
  92. return (List<T>) resultList;
  93. }
  94. public List<T> search(String filters) throws ParseException {
  95. URLQueryParser queryParser = createQueryParser("", filters, "");
  96. CriteriaQuery query = queryParser.makeCriteriaQuery();
  97. List resultList = entityManager
  98. .createQuery(query)
  99. .getResultList();
  100. return (List<T>) resultList;
  101. }
  102. public List<T> search(String filters, String sorts) throws ParseException {
  103. URLQueryParser queryParser = createQueryParser("", filters, sorts);
  104. CriteriaQuery query = queryParser.makeCriteriaQuery();
  105. List resultList = entityManager
  106. .createQuery(query)
  107. .getResultList();
  108. return (List<T>) resultList;
  109. }
  110. public long getCount(String filters) throws ParseException {
  111. URLQueryParser queryParser = createQueryParser(filters);
  112. CriteriaQuery query = queryParser.makeCriteriaCountQuery();
  113. return (long) entityManager.createQuery(query).getSingleResult();
  114. }
  115. public PagingAndSortingRepository getRepository() {
  116. return (PagingAndSortingRepository) SpringContext.getService(repoClass);
  117. }
  118. public JpaRepository getJpaRepository() {
  119. return (JpaRepository) SpringContext.getService(repoClass);
  120. }
  121. public List<T> findByField(String field, Object value) {
  122. return findByFields(
  123. new String[]{field},
  124. new Object[]{value}
  125. );
  126. }
  127. public List<T> findByFields(String[] fields, Object[] values) {
  128. CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
  129. CriteriaQuery query = criteriaBuilder.createQuery(getEntityClass());
  130. Root<T> root = query.from(getEntityClass());
  131. List<Predicate> ls = new ArrayList<>();
  132. for (int i = 0; i < fields.length; i++) {
  133. if (values[i].getClass().isArray()) {
  134. ls.add(criteriaBuilder.in(root.get(fields[i]).in((Object[]) values[i])));
  135. } else {
  136. ls.add(criteriaBuilder.equal(root.get(fields[i]), values[i]));
  137. }
  138. }
  139. query.where(ls.toArray(new Predicate[ls.size()]));
  140. List resultList = entityManager
  141. .createQuery(query)
  142. .getResultList();
  143. return (List<T>) resultList;
  144. }
  145. public String getClzName() {
  146. return getEntityClass().getName();
  147. }
  148. public String getEntityIdFiled() {
  149. EntityType entityType = entityManager.getMetamodel().entity(getEntityClass());
  150. javax.persistence.metamodel.Type type = entityType.getIdType();
  151. String s = entityType.getId(type.getJavaType()).getName();
  152. return s;
  153. }
  154. public int delete(Object[] ids) {
  155. String hql = " DELETE FROM " + getEntityClass().getName() + " WHERE " + getEntityIdFiled() + " in(:ids)";
  156. Query query = currentSession().createQuery(hql);
  157. query.setParameterList("ids", ids);
  158. return query.executeUpdate();
  159. }
  160. public void batchInsert(List list) {
  161. for (int i = 0; i < list.size(); i++) {
  162. entityManager.persist(list.get(i));
  163. if (i % 30 == 0) {
  164. entityManager.flush();
  165. entityManager.clear();
  166. }
  167. }
  168. }
  169. public String getCode() {
  170. return UUID.randomUUID().toString().replaceAll("-", "");
  171. }
  172. protected <t> URLQueryParser createQueryParser(String fields, String filters, String orders) {
  173. return new URLQueryParser<t>(fields, filters, orders)
  174. .setEntityManager(entityManager)
  175. .setEntityClass(getEntityClass());
  176. }
  177. protected <t> URLQueryParser createQueryParser(String filters) {
  178. return new URLQueryParser<t>(filters)
  179. .setEntityManager(entityManager)
  180. .setEntityClass(getEntityClass());
  181. }
  182. protected Sort parseSorts(String sorter) {
  183. if (StringUtils.isNotEmpty(sorter)) {
  184. String[] orderArray = sorter.split(",");
  185. List<Sort.Order> orderList = new ArrayList<>(orderArray.length);
  186. Arrays.stream(orderArray).forEach(
  187. elem -> orderList.add(
  188. elem.startsWith("+") ? new Sort.Order(Sort.Direction.ASC, elem.substring(1)) :
  189. new Sort.Order(Sort.Direction.DESC, elem.substring(1))));
  190. return new Sort(orderList);
  191. }
  192. return null;
  193. }
  194. protected Session currentSession() {
  195. return entityManager.unwrap(Session.class);
  196. }
  197. }