Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JpaDatabaseSession.java 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. * SonarQube, open source software quality management tool.
  3. * Copyright (C) 2008-2014 SonarSource
  4. * mailto:contact AT sonarsource DOT com
  5. *
  6. * SonarQube is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * SonarQube is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.jpa.session;
  21. import com.google.common.annotations.VisibleForTesting;
  22. import com.google.common.collect.Maps;
  23. import org.apache.commons.lang.StringUtils;
  24. import org.sonar.api.database.DatabaseSession;
  25. import javax.persistence.EntityManager;
  26. import javax.persistence.NonUniqueResultException;
  27. import javax.persistence.PersistenceException;
  28. import javax.persistence.Query;
  29. import java.util.*;
  30. public class JpaDatabaseSession extends DatabaseSession {
  31. private final DatabaseConnector connector;
  32. private EntityManager entityManager = null;
  33. private int index = 0;
  34. private boolean inTransaction = false;
  35. public JpaDatabaseSession(DatabaseConnector connector) {
  36. this.connector = connector;
  37. }
  38. /**
  39. * Note that usage of this method is discouraged, because it allows to construct and execute queries without additional exception handling,
  40. * which done in methods of this class.
  41. */
  42. @Override
  43. public EntityManager getEntityManager() {
  44. if (entityManager == null) {
  45. entityManager = connector.createEntityManager();
  46. }
  47. return entityManager;
  48. }
  49. @Override
  50. public void start() {
  51. getEntityManager();
  52. index = 0;
  53. }
  54. @Override
  55. public void stop() {
  56. commitAndClose();
  57. }
  58. @Override
  59. public void commitAndClose() {
  60. commit();
  61. if (entityManager != null && entityManager.isOpen()) {
  62. entityManager.close();
  63. entityManager = null;
  64. }
  65. }
  66. @Override
  67. public void commit() {
  68. if (inTransaction) {
  69. if (getEntityManager().isOpen()) {
  70. if (getEntityManager().getTransaction().getRollbackOnly()) {
  71. getEntityManager().getTransaction().rollback();
  72. } else {
  73. getEntityManager().getTransaction().commit();
  74. }
  75. getEntityManager().clear();
  76. index = 0;
  77. }
  78. inTransaction = false;
  79. }
  80. }
  81. @Override
  82. public void rollback() {
  83. if (inTransaction) {
  84. getEntityManager().getTransaction().rollback();
  85. inTransaction = false;
  86. }
  87. }
  88. @Override
  89. public <T> T save(T model) {
  90. startTransaction();
  91. internalSave(model, true);
  92. return model;
  93. }
  94. @Override
  95. public Object saveWithoutFlush(Object model) {
  96. startTransaction();
  97. internalSave(model, false);
  98. return model;
  99. }
  100. @Override
  101. public boolean contains(Object model) {
  102. startTransaction();
  103. return getEntityManager().contains(model);
  104. }
  105. @Override
  106. public void save(Object... models) {
  107. startTransaction();
  108. for (Object model : models) {
  109. save(model);
  110. }
  111. }
  112. private void internalSave(Object model, boolean flushIfNeeded) {
  113. try {
  114. getEntityManager().persist(model);
  115. } catch (PersistenceException e) {
  116. /*
  117. * See http://jira.sonarsource.com/browse/SONAR-2234
  118. * In some cases Hibernate can throw exceptions without meaningful information about context, so we improve them here.
  119. */
  120. throw new PersistenceException("Unable to persist : " + model, e);
  121. }
  122. if (flushIfNeeded && (++index % BATCH_SIZE == 0)) {
  123. commit();
  124. }
  125. }
  126. @Override
  127. public Object merge(Object model) {
  128. startTransaction();
  129. return getEntityManager().merge(model);
  130. }
  131. @Override
  132. public void remove(Object model) {
  133. startTransaction();
  134. getEntityManager().remove(model);
  135. if (++index % BATCH_SIZE == 0) {
  136. commit();
  137. }
  138. }
  139. @Override
  140. public void removeWithoutFlush(Object model) {
  141. startTransaction();
  142. getEntityManager().remove(model);
  143. }
  144. @Override
  145. public <T> T reattach(Class<T> entityClass, Object primaryKey) {
  146. startTransaction();
  147. return getEntityManager().getReference(entityClass, primaryKey);
  148. }
  149. private void startTransaction() {
  150. if (!inTransaction) {
  151. getEntityManager().getTransaction().begin();
  152. inTransaction = true;
  153. }
  154. }
  155. /**
  156. * Note that not recommended to directly execute {@link Query#getSingleResult()}, because it will bypass exception handling,
  157. * which done in {@link #getSingleResult(Query, Object)}.
  158. */
  159. @Override
  160. public Query createQuery(String hql) {
  161. startTransaction();
  162. return getEntityManager().createQuery(hql);
  163. }
  164. @Override
  165. public Query createNativeQuery(String sql) {
  166. startTransaction();
  167. return getEntityManager().createNativeQuery(sql);
  168. }
  169. /**
  170. * @return the result or <code>defaultValue</code>, if not found
  171. * @throws NonUniqueResultException if more than one result
  172. */
  173. @Override
  174. public <T> T getSingleResult(Query query, T defaultValue) {
  175. /*
  176. * See http://jira.sonarsource.com/browse/SONAR-2225
  177. * By default Hibernate throws NonUniqueResultException without meaningful information about context,
  178. * so we improve it here by adding all results in error message.
  179. * Note that in some rare situations we can receive too many results, which may lead to OOME,
  180. * but actually it will mean that database is corrupted as we don't expect more than one result
  181. * and in fact org.hibernate.ejb.QueryImpl#getSingleResult() anyway does loading of several results under the hood.
  182. */
  183. List<T> result = query.getResultList();
  184. if (result.size() == 1) {
  185. return result.get(0);
  186. } else if (result.isEmpty()) {
  187. return defaultValue;
  188. } else {
  189. Set<T> uniqueResult = new HashSet<>(result);
  190. if (uniqueResult.size() > 1) {
  191. throw new NonUniqueResultException("Expected single result, but got : " + result.toString());
  192. } else {
  193. return uniqueResult.iterator().next();
  194. }
  195. }
  196. }
  197. @Override
  198. public <T> T getEntity(Class<T> entityClass, Object id) {
  199. startTransaction();
  200. return getEntityManager().find(entityClass, id);
  201. }
  202. /**
  203. * @return the result or <code>null</code>, if not found
  204. * @throws NonUniqueResultException if more than one result
  205. */
  206. @Override
  207. public <T> T getSingleResult(Class<T> entityClass, Object... criterias) {
  208. try {
  209. return getSingleResult(getQueryForCriterias(entityClass, true, criterias), (T) null);
  210. } catch (NonUniqueResultException ex) {
  211. NonUniqueResultException e = new NonUniqueResultException("Expected single result for entitiy " + entityClass.getSimpleName()
  212. + " with criterias : " + StringUtils.join(criterias, ","));
  213. throw (NonUniqueResultException) e.initCause(ex);
  214. }
  215. }
  216. @Override
  217. public <T> List<T> getResults(Class<T> entityClass, Object... criterias) {
  218. return getQueryForCriterias(entityClass, true, criterias).getResultList();
  219. }
  220. @Override
  221. public <T> List<T> getResults(Class<T> entityClass) {
  222. return getQueryForCriterias(entityClass, false, (Object[]) null).getResultList();
  223. }
  224. private Query getQueryForCriterias(Class<?> entityClass, boolean raiseError, Object... criterias) {
  225. if (criterias == null && raiseError) {
  226. throw new IllegalStateException("criterias parameter must be provided");
  227. }
  228. startTransaction();
  229. StringBuilder hql = new StringBuilder("SELECT o FROM ").append(entityClass.getSimpleName()).append(" o");
  230. if (criterias != null) {
  231. hql.append(" WHERE ");
  232. Map<String, Object> mappedCriterias = Maps.newHashMap();
  233. for (int i = 0; i < criterias.length; i += 2) {
  234. mappedCriterias.put((String) criterias[i], criterias[i + 1]);
  235. }
  236. buildCriteriasHQL(hql, mappedCriterias);
  237. Query query = getEntityManager().createQuery(hql.toString());
  238. for (Map.Entry<String, Object> entry : mappedCriterias.entrySet()) {
  239. if (entry.getValue() != null) {
  240. query.setParameter(entry.getKey(), entry.getValue());
  241. }
  242. }
  243. return query;
  244. }
  245. return getEntityManager().createQuery(hql.toString());
  246. }
  247. @VisibleForTesting
  248. void buildCriteriasHQL(StringBuilder hql, Map<String, Object> mappedCriterias) {
  249. for (Iterator<Map.Entry<String, Object>> i = mappedCriterias.entrySet().iterator(); i.hasNext();) {
  250. Map.Entry<String, Object> entry = i.next();
  251. hql.append("o.").append(entry.getKey());
  252. if (entry.getValue() == null) {
  253. hql.append(" IS NULL");
  254. } else {
  255. hql.append("=:").append(entry.getKey());
  256. }
  257. if (i.hasNext()) {
  258. hql.append(" AND ");
  259. }
  260. }
  261. }
  262. }