diff --git a/.github/workflows/run-api-tests.yml b/.github/workflows/run-api-tests.yml index e56e860f45b6..92a760844b4d 100644 --- a/.github/workflows/run-api-tests.yml +++ b/.github/workflows/run-api-tests.yml @@ -8,7 +8,6 @@ on: branches: - master pull_request: - types: [ opened, labeled, synchronize ] concurrency: group: ${{ github.workflow}}-${{ github.ref }} cancel-in-progress: true @@ -20,7 +19,6 @@ jobs: CORE_IMAGE_NAME: "dhis2/core-pr:${{ github.event_name == 'pull_request' && github.event.number || 'local' }}" runs-on: ubuntu-latest - if: "!contains(github.event.pull_request.labels.*.name, 'skip-api-tests')" steps: - uses: actions/checkout@v4 - name: Set up JDK 17 diff --git a/dhis-2/build.sh b/dhis-2/build.sh old mode 100755 new mode 100644 diff --git a/dhis-2/dhis-api/pom.xml b/dhis-2/dhis-api/pom.xml index 397c0d4399e9..7de32b7e5330 100644 --- a/dhis-2/dhis-api/pom.xml +++ b/dhis-2/dhis-api/pom.xml @@ -97,6 +97,10 @@ org.hisp.dhis.rules rule-engine + + org.hisp.dhis + json-tree + org.springframework.security spring-security-core diff --git a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/dbms/DbmsManager.java b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/dbms/DbmsManager.java index 76bef5f0b5c0..8ef144ee811c 100644 --- a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/dbms/DbmsManager.java +++ b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/dbms/DbmsManager.java @@ -27,7 +27,6 @@ */ package org.hisp.dhis.dbms; -import java.io.Serializable; import java.util.List; /** @@ -47,10 +46,4 @@ public interface DbmsManager { boolean tableExists(String tableName); List> getTableContent(String table); - - void evictObject(Object object); - - boolean contains(Object object); - - Serializable getIdentifier(Object object); } diff --git a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/reservedvalue/ReservedValueStore.java b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/reservedvalue/ReservedValueStore.java index 671b26bd163e..a86d3f897706 100644 --- a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/reservedvalue/ReservedValueStore.java +++ b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/reservedvalue/ReservedValueStore.java @@ -42,8 +42,6 @@ public interface ReservedValueStore extends GenericStore { List getAvailableValues( ReservedValue reservedValue, List values, String ownerObject); - List reserveValuesJpa(ReservedValue reservedValue, List values); - int getNumberOfUsedValues(ReservedValue reservedValue); boolean useReservedValue(String ownerUID, String value); diff --git a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobConfigurationService.java b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobConfigurationService.java index fd12a9b467d2..0e62820ab32d 100644 --- a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobConfigurationService.java +++ b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobConfigurationService.java @@ -30,7 +30,9 @@ import java.io.InputStream; import java.util.List; import java.util.Map; +import javax.annotation.Nonnull; import org.hisp.dhis.feedback.ConflictException; +import org.hisp.dhis.jsontree.JsonObject; import org.hisp.dhis.schema.Property; import org.springframework.util.MimeType; @@ -160,6 +162,13 @@ String create(JobConfiguration config, MimeType contentType, InputStream content */ List getStaleConfigurations(int staleForSeconds); + /** + * @param params query parameters (criteria) to find + * @return all job configurations that match the query parameters + */ + @Nonnull + List findJobRunErrors(@Nonnull JobRunErrorsParams params); + /** * Get a map of parameter classes with appropriate properties This can be used for a frontend app * or for other appropriate applications which needs information about the jobs in the system. diff --git a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobConfigurationStore.java b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobConfigurationStore.java index a0d90d73df58..40402cdd79db 100644 --- a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobConfigurationStore.java +++ b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobConfigurationStore.java @@ -115,6 +115,13 @@ public interface JobConfigurationStore extends GenericDimensionalObjectStore getDueJobConfigurations(boolean includeWaiting); + /** + * @param params query parameters (criteria) to find + * @return all job configurations that match the query parameters + */ + @Nonnull + Stream findJobRunErrors(@Nonnull JobRunErrorsParams params); + /** * @return A list of all job types that are currently in {@link JobStatus#RUNNING} state. */ diff --git a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobProgress.java b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobProgress.java index 932cbf92a6f7..ee0f14d50f0f 100644 --- a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobProgress.java +++ b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobProgress.java @@ -142,12 +142,18 @@ default boolean isSkipCurrentStage() { Error reporting API: */ - default void addError(ErrorCode code, String uid, String type, Integer index, String... args) { - addError(code, uid, type, index, List.of(args)); + default void addError( + @Nonnull ErrorCode code, @CheckForNull String uid, @Nonnull String type, String... args) { + addError(code, uid, type, List.of(args)); } - default void addError(ErrorCode code, String uid, String type, Integer index, List args) { - // default implementation is a NOOP, we don't remember or handle the error + default void addError( + @Nonnull ErrorCode code, + @CheckForNull String uid, + @Nonnull String type, + @Nonnull List args) { + // is overridden by a tracker that collects errors + // default is to not collect errors } /* @@ -590,10 +596,13 @@ public Progress( } public void addError(Error error) { - errors - .computeIfAbsent(error.getId(), key -> new ConcurrentHashMap<>()) - .computeIfAbsent(error.getCode(), key2 -> new ConcurrentLinkedQueue<>()) - .add(error); + Queue sameObjectAndCode = + errors + .computeIfAbsent(error.getId(), key -> new ConcurrentHashMap<>()) + .computeIfAbsent(error.getCode(), key2 -> new ConcurrentLinkedQueue<>()); + if (sameObjectAndCode.stream().noneMatch(e -> e.args.equals(error.args))) { + sameObjectAndCode.add(error); + } } public boolean hasErrors() { @@ -619,13 +628,6 @@ final class Error { /** The type of the object identified by #id that has the error */ @Nonnull @JsonProperty private final String type; - /** - * The row index in the payload of the import. This is the index in the list of objects of a - * single type. This means the same index occurs for each object type. For some imports this - * information is not available. - */ - @CheckForNull @JsonProperty private final Integer index; - /** The arguments used in the {@link #code}'s {@link ErrorCode#getMessage()} template */ @Nonnull @JsonProperty private final List args; @@ -642,12 +644,10 @@ public Error( @Nonnull @JsonProperty("code") ErrorCode code, @Nonnull @JsonProperty("id") String id, @Nonnull @JsonProperty("type") String type, - @CheckForNull @JsonProperty("index") Integer index, @Nonnull @JsonProperty("args") List args) { this.code = code; this.id = id; this.type = type; - this.index = index; this.args = args; } } diff --git a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobRunErrorsParams.java b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobRunErrorsParams.java new file mode 100644 index 000000000000..f7d0f28c74e1 --- /dev/null +++ b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/scheduling/JobRunErrorsParams.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2004-2023, University of Oslo + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of the HISP project nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.hisp.dhis.scheduling; + +import java.util.Date; +import java.util.List; +import javax.annotation.CheckForNull; +import lombok.Data; +import lombok.experimental.Accessors; +import org.hisp.dhis.common.OpenApi; +import org.hisp.dhis.common.UID; +import org.hisp.dhis.feedback.ErrorCode; +import org.hisp.dhis.user.User; + +/** + * Query params when searching for {@link JobConfiguration}s with errors. + * + *

A match has to satisfy all filters (AND logic) but only one of the given codes or object + * {@link UID} (OR logic). + * + *

If any of the criteria is not defined it has no filter effect. + * + * @author Jan Bernitt + */ +@Data +@Accessors(chain = true) +public class JobRunErrorsParams { + + @OpenApi.Ignore @CheckForNull private UID job; + + /** The user that ran the job */ + @OpenApi.Property({UID.class, User.class}) + @CheckForNull + private UID user; + + /** The earliest date the job ran that should be included */ + @CheckForNull private Date from; + + /** The latest date the job ran that should be included */ + @CheckForNull private Date to; + + /** The codes to select, any match combined */ + @CheckForNull private List code; + + /** The object with errors to select, any match combined */ + @CheckForNull private List object; + + /** The {@link JobType} with errors to select, any match combined */ + @CheckForNull private List type; +} diff --git a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/user/CurrentUserService.java b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/user/CurrentUserService.java index 1c560dd94c4d..df8ca46c6d5c 100644 --- a/dhis-2/dhis-api/src/main/java/org/hisp/dhis/user/CurrentUserService.java +++ b/dhis-2/dhis-api/src/main/java/org/hisp/dhis/user/CurrentUserService.java @@ -73,6 +73,7 @@ public String getCurrentUsername() { return CurrentUserUtil.getCurrentUsername(); } + @Transactional(readOnly = true) public User getCurrentUser() { String username = CurrentUserUtil.getCurrentUsername(); diff --git a/dhis-2/dhis-services/dhis-service-administration/pom.xml b/dhis-2/dhis-services/dhis-service-administration/pom.xml index db0a5aa361f9..9b4523cb4c35 100644 --- a/dhis-2/dhis-services/dhis-service-administration/pom.xml +++ b/dhis-2/dhis-services/dhis-service-administration/pom.xml @@ -101,8 +101,8 @@ test - org.hibernate - hibernate-core + javax.persistence + javax.persistence-api org.slf4j diff --git a/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/dataintegrity/hibernate/HibernateDataIntegrityStore.java b/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/dataintegrity/hibernate/HibernateDataIntegrityStore.java index dc98614ed971..7357f7c4f0d4 100644 --- a/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/dataintegrity/hibernate/HibernateDataIntegrityStore.java +++ b/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/dataintegrity/hibernate/HibernateDataIntegrityStore.java @@ -31,8 +31,9 @@ import java.util.Date; import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import lombok.RequiredArgsConstructor; -import org.hibernate.SessionFactory; import org.hisp.dhis.dataintegrity.DataIntegrityCheck; import org.hisp.dhis.dataintegrity.DataIntegrityDetails; import org.hisp.dhis.dataintegrity.DataIntegrityDetails.DataIntegrityIssue; @@ -50,13 +51,13 @@ @Repository @RequiredArgsConstructor public class HibernateDataIntegrityStore implements DataIntegrityStore { - private final SessionFactory sessionFactory; + @PersistenceContext private final EntityManager entityManager; @Override @Transactional(readOnly = true) public DataIntegritySummary querySummary(DataIntegrityCheck check, String sql) { Date startTime = new Date(); - Object summary = sessionFactory.getCurrentSession().createNativeQuery(sql).getSingleResult(); + Object summary = entityManager.createNativeQuery(sql).getSingleResult(); return new DataIntegritySummary( check, startTime, new Date(), null, parseCount(summary), parsePercentage(summary)); } @@ -66,7 +67,7 @@ public DataIntegritySummary querySummary(DataIntegrityCheck check, String sql) { public DataIntegrityDetails queryDetails(DataIntegrityCheck check, String sql) { Date startTime = new Date(); @SuppressWarnings("unchecked") - List rows = sessionFactory.getCurrentSession().createNativeQuery(sql).getResultList(); + List rows = entityManager.createNativeQuery(sql).getResultList(); return new DataIntegrityDetails( check, startTime, diff --git a/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/merge/orgunit/handler/DataOrgUnitMergeHandler.java b/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/merge/orgunit/handler/DataOrgUnitMergeHandler.java index 9bf264b697bc..dd5a36169d38 100644 --- a/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/merge/orgunit/handler/DataOrgUnitMergeHandler.java +++ b/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/merge/orgunit/handler/DataOrgUnitMergeHandler.java @@ -29,8 +29,8 @@ import static org.hisp.dhis.common.IdentifiableObjectUtils.getIdentifiers; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.IdentifiableObjectUtils; import org.hisp.dhis.dataapproval.DataApprovalAuditService; import org.hisp.dhis.dataset.DataSetService; @@ -55,7 +55,7 @@ @Transactional @RequiredArgsConstructor public class DataOrgUnitMergeHandler { - private final SessionFactory sessionFactory; + private final EntityManager entityManager; private final NamedParameterJdbcTemplate jdbcTemplate; @@ -201,11 +201,10 @@ public void mergeInterpretations(OrgUnitMergeRequest request) { } private void migrate(String hql, OrgUnitMergeRequest request) { - sessionFactory - .getCurrentSession() + entityManager .createQuery(hql) .setParameter("target", request.getTarget()) - .setParameterList("sources", IdentifiableObjectUtils.getIdentifiers(request.getSources())) + .setParameter("sources", IdentifiableObjectUtils.getIdentifiers(request.getSources())) .executeUpdate(); } } diff --git a/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/merge/orgunit/handler/TrackerOrgUnitMergeHandler.java b/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/merge/orgunit/handler/TrackerOrgUnitMergeHandler.java index 4bf2fb25200b..fa480392e10f 100644 --- a/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/merge/orgunit/handler/TrackerOrgUnitMergeHandler.java +++ b/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/merge/orgunit/handler/TrackerOrgUnitMergeHandler.java @@ -27,8 +27,8 @@ */ package org.hisp.dhis.merge.orgunit.handler; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.IdentifiableObjectUtils; import org.hisp.dhis.merge.orgunit.OrgUnitMergeRequest; import org.springframework.stereotype.Service; @@ -42,7 +42,7 @@ @Service @RequiredArgsConstructor public class TrackerOrgUnitMergeHandler { - private final SessionFactory sessionFactory; + private final EntityManager entityManager; @Transactional public void mergeProgramMessages(OrgUnitMergeRequest request) { @@ -90,11 +90,10 @@ public void mergeTrackedEntities(OrgUnitMergeRequest request) { } private void migrate(String hql, OrgUnitMergeRequest request) { - sessionFactory - .getCurrentSession() + entityManager .createQuery(hql) .setParameter("target", request.getTarget()) - .setParameterList("sources", IdentifiableObjectUtils.getIdentifiers(request.getSources())) + .setParameter("sources", IdentifiableObjectUtils.getIdentifiers(request.getSources())) .executeUpdate(); } } diff --git a/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/split/orgunit/handler/DataOrgUnitSplitHandler.java b/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/split/orgunit/handler/DataOrgUnitSplitHandler.java index 63a5ec027735..54ac9240e326 100644 --- a/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/split/orgunit/handler/DataOrgUnitSplitHandler.java +++ b/dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/split/orgunit/handler/DataOrgUnitSplitHandler.java @@ -27,9 +27,9 @@ */ package org.hisp.dhis.split.orgunit.handler; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.hibernate.SessionFactory; import org.hisp.dhis.split.orgunit.OrgUnitSplitRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -46,7 +46,7 @@ public class DataOrgUnitSplitHandler { private static final String PARAM_SOURCE = "source"; - private final SessionFactory sessionFactory; + private final EntityManager entityManager; @Transactional public void splitData(OrgUnitSplitRequest request) { @@ -74,8 +74,7 @@ private void migrate(OrgUnitSplitRequest request, String entity, String property log.debug("Update data HQL: '{}'", hql); - sessionFactory - .getCurrentSession() + entityManager .createQuery(hql) .setParameter("source", request.getSource()) .setParameter("target", request.getPrimaryTarget()) diff --git a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEnrollmentAnalyticsTableManager.java b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEnrollmentAnalyticsTableManager.java index 826dfe59944a..be49e8fb3cb8 100644 --- a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEnrollmentAnalyticsTableManager.java +++ b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEnrollmentAnalyticsTableManager.java @@ -107,7 +107,7 @@ public JdbcEnrollmentAnalyticsTableManager( List.of( new AnalyticsTableColumn(quote("pi"), CHARACTER_11, NOT_NULL, "pi.uid"), new AnalyticsTableColumn(quote("enrollmentdate"), TIMESTAMP, "pi.enrollmentdate"), - new AnalyticsTableColumn(quote("incidentdate"), TIMESTAMP, "pi.incidentdate"), + new AnalyticsTableColumn(quote("incidentdate"), TIMESTAMP, "pi.occurreddate"), new AnalyticsTableColumn( quote("completeddate"), TIMESTAMP, @@ -228,7 +228,7 @@ protected void populateTable( + "and pi.lastupdated <= '" + getLongDateString(params.getStartTime()) + "' " - + "and pi.incidentdate is not null " + + "and pi.occurreddate is not null " + "and pi.deleted is false "; populateTableInternal(partition, getDimensionColumns(program), fromClause); diff --git a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEventAnalyticsTableManager.java b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEventAnalyticsTableManager.java index 242f5220926d..4e1d88945055 100644 --- a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEventAnalyticsTableManager.java +++ b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEventAnalyticsTableManager.java @@ -140,7 +140,7 @@ public JdbcEventAnalyticsTableManager( new AnalyticsTableColumn(quote("ps"), CHARACTER_11, NOT_NULL, "ps.uid"), new AnalyticsTableColumn(quote("ao"), CHARACTER_11, NOT_NULL, "ao.uid"), new AnalyticsTableColumn(quote("enrollmentdate"), TIMESTAMP, "pi.enrollmentdate"), - new AnalyticsTableColumn(quote("incidentdate"), TIMESTAMP, "pi.incidentdate"), + new AnalyticsTableColumn(quote("incidentdate"), TIMESTAMP, "pi.occurreddate"), new AnalyticsTableColumn(quote("occurreddate"), TIMESTAMP, "psi.occurreddate"), new AnalyticsTableColumn(quote("scheduleddate"), TIMESTAMP, "psi.scheduleddate"), new AnalyticsTableColumn(quote("completeddate"), TIMESTAMP, "psi.completeddate"), diff --git a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcOwnershipAnalyticsTableManager.java b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcOwnershipAnalyticsTableManager.java index be2333f65c91..6c8c718a1ec4 100644 --- a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcOwnershipAnalyticsTableManager.java +++ b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcOwnershipAnalyticsTableManager.java @@ -178,30 +178,32 @@ private void populateTableInternal(AnalyticsTablePartition partition, String sql List columnNames = getDimensionColumns().stream().map(AnalyticsTableColumn::getName).collect(toList()); - MappingBatchHandler batchHandler = + try (MappingBatchHandler batchHandler = MappingBatchHandler.builder() .jdbcConfiguration(jdbcConfiguration) .tableName(partition.getTempTableName()) .columns(columnNames) - .build(); - - batchHandler.init(); - - JdbcOwnershipWriter writer = JdbcOwnershipWriter.getInstance(batchHandler); - AtomicInteger queryRowCount = new AtomicInteger(); - - jdbcTemplate.query( - sql, - resultSet -> { - writer.write(getRowMap(columnNames, resultSet)); - queryRowCount.getAndIncrement(); - }); - - log.info( - "OwnershipAnalytics query row count was {} for {}", - queryRowCount, - partition.getTempTableName()); - batchHandler.flush(); + .build()) { + batchHandler.init(); + + JdbcOwnershipWriter writer = JdbcOwnershipWriter.getInstance(batchHandler); + AtomicInteger queryRowCount = new AtomicInteger(); + + jdbcTemplate.query( + sql, + resultSet -> { + writer.write(getRowMap(columnNames, resultSet)); + queryRowCount.getAndIncrement(); + }); + + log.info( + "OwnershipAnalytics query row count was {} for {}", + queryRowCount, + partition.getTempTableName()); + batchHandler.flush(); + } catch (Exception ex) { + log.error("Failed to alter table ownership: ", ex); + } } private String getInputSql(Program program) { diff --git a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcTeiEnrollmentsAnalyticsTableManager.java b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcTeiEnrollmentsAnalyticsTableManager.java index 8825abcfae9b..1a67795566b0 100644 --- a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcTeiEnrollmentsAnalyticsTableManager.java +++ b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcTeiEnrollmentsAnalyticsTableManager.java @@ -121,7 +121,7 @@ public JdbcTeiEnrollmentsAnalyticsTableManager( new AnalyticsTableColumn(quote("programinstanceuid"), CHARACTER_11, NULL, "pi.uid"), new AnalyticsTableColumn(quote("enrollmentdate"), TIMESTAMP, "pi.enrollmentdate"), new AnalyticsTableColumn(quote("enddate"), TIMESTAMP, "pi.completeddate"), - new AnalyticsTableColumn(quote("incidentdate"), TIMESTAMP, "pi.incidentdate"), + new AnalyticsTableColumn(quote("incidentdate"), TIMESTAMP, "pi.occurreddate"), new AnalyticsTableColumn(quote("enrollmentstatus"), VARCHAR_50, "pi.status"), new AnalyticsTableColumn(quote("pigeometry"), GEOMETRY, "pi.geometry") .withIndexType(GIST), @@ -256,7 +256,7 @@ protected void populateTable( + " and psi.status in (" + join(",", EXPORTABLE_EVENT_STATUSES) + "))") - .append(" and pi.incidentdate is not null ") + .append(" and pi.occurreddate is not null ") .append(" and pi.deleted is false"); invokeTimeAndLog(sql.toString(), partition.getTempTableName()); diff --git a/dhis-2/dhis-services/dhis-service-core/pom.xml b/dhis-2/dhis-services/dhis-service-core/pom.xml index 67b693b9aacb..4110907e6117 100644 --- a/dhis-2/dhis-services/dhis-service-core/pom.xml +++ b/dhis-2/dhis-services/dhis-service-core/pom.xml @@ -117,6 +117,11 @@ org.hibernate hibernate-core + + com.vladmihalcea + hibernate-types-52 + ${hibernate-types.version} + com.fasterxml.jackson.core jackson-core diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/analytics/hibernate/HibernateAnalyticsTableHookStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/analytics/hibernate/HibernateAnalyticsTableHookStore.java index 7185f8d4949a..281eaaed94b1 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/analytics/hibernate/HibernateAnalyticsTableHookStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/analytics/hibernate/HibernateAnalyticsTableHookStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.analytics.hibernate; import java.util.List; +import javax.persistence.EntityManager; import lombok.extern.slf4j.Slf4j; -import org.hibernate.SessionFactory; import org.hisp.dhis.analytics.AnalyticsTableHook; import org.hisp.dhis.analytics.AnalyticsTableHookStore; import org.hisp.dhis.analytics.AnalyticsTablePhase; @@ -51,13 +51,13 @@ public class HibernateAnalyticsTableHookStore extends HibernateIdentifiableObjectStore implements AnalyticsTableHookStore { public HibernateAnalyticsTableHookStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, AnalyticsTableHook.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/attribute/hibernate/HibernateAttributeStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/attribute/hibernate/HibernateAttributeStore.java index 1d4d7f50463b..19a88e4969f3 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/attribute/hibernate/HibernateAttributeStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/attribute/hibernate/HibernateAttributeStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.attribute.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.attribute.Attribute; import org.hisp.dhis.attribute.AttributeStore; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; @@ -46,13 +46,13 @@ public class HibernateAttributeStore extends HibernateIdentifiableObjectStore implements CategoryComboStore { public HibernateCategoryComboStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, CategoryCombo.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionComboStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionComboStore.java index d11299fff400..965b1442ddb9 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionComboStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionComboStore.java @@ -29,9 +29,9 @@ import java.util.List; import java.util.Set; +import javax.persistence.EntityManager; import org.hibernate.NonUniqueResultException; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.category.CategoryOption; @@ -56,14 +56,14 @@ public class HibernateCategoryOptionComboStore private final DbmsManager dbmsManager; public HibernateCategoryOptionComboStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService, DbmsManager dbmsManager) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, CategoryOptionCombo.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionGroupSetStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionGroupSetStore.java index de1a6f36f7a8..b87c13ed83e7 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionGroupSetStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionGroupSetStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.category.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.CategoryOptionGroupSet; import org.hisp.dhis.category.CategoryOptionGroupSetStore; import org.hisp.dhis.common.DataDimensionType; @@ -48,13 +48,13 @@ public class HibernateCategoryOptionGroupSetStore extends HibernateIdentifiableObjectStore implements CategoryOptionGroupSetStore { public HibernateCategoryOptionGroupSetStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, CategoryOptionGroupSet.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionGroupStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionGroupStore.java index 50be5f4ec949..e1079efb9a5b 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionGroupStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionGroupStore.java @@ -28,9 +28,9 @@ package org.hisp.dhis.category.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Join; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.CategoryOptionGroup; import org.hisp.dhis.category.CategoryOptionGroupSet; import org.hisp.dhis.category.CategoryOptionGroupStore; @@ -50,13 +50,13 @@ public class HibernateCategoryOptionGroupStore extends HibernateIdentifiableObjectStore implements CategoryOptionGroupStore { public HibernateCategoryOptionGroupStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, CategoryOptionGroup.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionStore.java index dc6270bc5b8d..dfa171f5d846 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryOptionStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.category.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.Category; import org.hisp.dhis.category.CategoryOption; import org.hisp.dhis.category.CategoryOptionStore; @@ -48,13 +48,13 @@ public class HibernateCategoryOptionStore extends HibernateIdentifiableObjectStore implements CategoryOptionStore { public HibernateCategoryOptionStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, CategoryOption.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryStore.java index 3e47110583a3..676c7a41d64a 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/category/hibernate/HibernateCategoryStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.category.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.Category; import org.hisp.dhis.category.CategoryStore; import org.hisp.dhis.common.DataDimensionType; @@ -47,13 +47,13 @@ public class HibernateCategoryStore extends HibernateIdentifiableObjectStore implements CategoryStore { public HibernateCategoryStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, Category.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/DefaultIdentifiableObjectManager.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/DefaultIdentifiableObjectManager.java index f0a85cf6e5b5..71081326c4d6 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/DefaultIdentifiableObjectManager.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/DefaultIdentifiableObjectManager.java @@ -51,10 +51,10 @@ import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; +import javax.persistence.EntityManager; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hibernate.proxy.HibernateProxy; import org.hisp.dhis.attribute.Attribute; import org.hisp.dhis.attribute.AttributeValue; @@ -100,7 +100,7 @@ public class DefaultIdentifiableObjectManager implements IdentifiableObjectManag private final Set> dimensionalObjectStores; - private final SessionFactory sessionFactory; + private final EntityManager entityManager; private final CurrentUserService currentUserService; @@ -119,20 +119,20 @@ public class DefaultIdentifiableObjectManager implements IdentifiableObjectManag public DefaultIdentifiableObjectManager( Set> identifiableObjectStores, Set> dimensionalObjectStores, - SessionFactory sessionFactory, + EntityManager entityManager, CurrentUserService currentUserService, SchemaService schemaService, CacheProvider cacheProvider) { checkNotNull(identifiableObjectStores); checkNotNull(dimensionalObjectStores); - checkNotNull(sessionFactory); + checkNotNull(entityManager); checkNotNull(currentUserService); checkNotNull(schemaService); checkNotNull(cacheProvider); this.identifiableObjectStores = identifiableObjectStores; this.dimensionalObjectStores = dimensionalObjectStores; - this.sessionFactory = sessionFactory; + this.entityManager = entityManager; this.currentUserService = currentUserService; this.schemaService = schemaService; this.defaultObjectCache = cacheProvider.createDefaultObjectCache(); @@ -202,8 +202,6 @@ public void update(@Nonnull List objects, @CheckForNull User @Transactional public void updateTranslations( @Nonnull IdentifiableObject persistedObject, @Nonnull Set translations) { - Session session = sessionFactory.getCurrentSession(); - BaseIdentifiableObject translatedObject = (BaseIdentifiableObject) persistedObject; translatedObject.setTranslations( @@ -214,7 +212,7 @@ public void updateTranslations( translatedObject.setLastUpdated(new Date()); translatedObject.setLastUpdatedBy(currentUserService.getCurrentUser()); - session.update(translatedObject); + entityManager.unwrap(Session.class).update(translatedObject); } @Override @@ -954,7 +952,7 @@ public IdentifiableObject getObject(long id, @Nonnull String simpleClassName) { @Override @Transactional public void refresh(@Nonnull Object object) { - sessionFactory.getCurrentSession().refresh(object); + entityManager.refresh(object); } @Override @@ -988,19 +986,19 @@ public void resetNonOwnerProperties(@Nonnull Object object) { @Override @Transactional public void flush() { - sessionFactory.getCurrentSession().flush(); + entityManager.flush(); } @Override @Transactional public void clear() { - sessionFactory.getCurrentSession().clear(); + entityManager.clear(); } @Override @Transactional public void evict(@Nonnull Object object) { - sessionFactory.getCurrentSession().evict(object); + entityManager.unwrap(Session.class).evict(object); } @Override diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/HibernateAnalyticalObjectStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/HibernateAnalyticalObjectStore.java index cb2c63afa010..5883e1299939 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/HibernateAnalyticalObjectStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/HibernateAnalyticalObjectStore.java @@ -28,7 +28,7 @@ package org.hisp.dhis.common.hibernate; import java.util.List; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hibernate.query.Query; import org.hisp.dhis.category.CategoryOptionGroup; import org.hisp.dhis.common.AnalyticalObjectStore; @@ -56,15 +56,14 @@ public class HibernateAnalyticalObjectStore extends HibernateIdentifiableObjectStore implements AnalyticalObjectStore { public HibernateAnalyticalObjectStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, Class clazz, CurrentUserService currentUserService, AclService aclService, boolean cacheable) { - super( - sessionFactory, jdbcTemplate, publisher, clazz, currentUserService, aclService, cacheable); + super(entityManager, jdbcTemplate, publisher, clazz, currentUserService, aclService, cacheable); } @Override diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/HibernateIdentifiableObjectStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/HibernateIdentifiableObjectStore.java index a7aa38b83da9..86e2ece2b8fa 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/HibernateIdentifiableObjectStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/HibernateIdentifiableObjectStore.java @@ -36,6 +36,7 @@ import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; +import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; @@ -44,7 +45,6 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; -import org.hibernate.SessionFactory; import org.hisp.dhis.attribute.Attribute; import org.hisp.dhis.common.AuditLogUtil; import org.hisp.dhis.common.BaseIdentifiableObject; @@ -79,15 +79,14 @@ public class HibernateIdentifiableObjectStore protected boolean transientIdentifiableProperties = false; public HibernateIdentifiableObjectStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, Class clazz, CurrentUserService currentUserService, AclService aclService, boolean cacheable) { - super( - sessionFactory, jdbcTemplate, publisher, clazz, aclService, currentUserService, cacheable); + super(entityManager, jdbcTemplate, publisher, clazz, aclService, currentUserService, cacheable); this.cacheable = cacheable; } @@ -186,7 +185,6 @@ public void update(@Nonnull T object, @CheckForNull User user) { } AuditLogUtil.infoWrapper(log, username, object, AuditLogUtil.ACTION_UPDATE); - getSession().update(object); } diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/InternalHibernateGenericStoreImpl.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/InternalHibernateGenericStoreImpl.java index 9bb248724279..9cda97a8b5bc 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/InternalHibernateGenericStoreImpl.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/InternalHibernateGenericStoreImpl.java @@ -34,10 +34,10 @@ import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.adapter.BaseIdentifiableObject_; import org.hisp.dhis.common.adapter.Sharing_; @@ -65,14 +65,14 @@ public class InternalHibernateGenericStoreImpl protected final CurrentUserService currentUserService; public InternalHibernateGenericStoreImpl( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, Class clazz, AclService aclService, CurrentUserService currentUserService, boolean cacheable) { - super(sessionFactory, jdbcTemplate, publisher, clazz, cacheable); + super(entityManager, jdbcTemplate, publisher, clazz, cacheable); checkNotNull(aclService); checkNotNull(currentUserService); diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/SharingHibernateGenericStoreImpl.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/SharingHibernateGenericStoreImpl.java index 9aedb3d55080..7b9575f49122 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/SharingHibernateGenericStoreImpl.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/SharingHibernateGenericStoreImpl.java @@ -30,10 +30,10 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Function; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.hibernate.SharingHibernateGenericStore; import org.hisp.dhis.security.acl.AclService; @@ -50,15 +50,14 @@ public class SharingHibernateGenericStoreImpl extends InternalHibernateGenericStoreImpl implements SharingHibernateGenericStore { public SharingHibernateGenericStoreImpl( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, Class clazz, AclService aclService, CurrentUserService currentUserService, boolean cacheable) { - super( - sessionFactory, jdbcTemplate, publisher, clazz, aclService, currentUserService, cacheable); + super(entityManager, jdbcTemplate, publisher, clazz, aclService, currentUserService, cacheable); } @Override diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/SoftDeleteHibernateObjectStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/SoftDeleteHibernateObjectStore.java index 6599be0a9c91..e26c48f22046 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/SoftDeleteHibernateObjectStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/hibernate/SoftDeleteHibernateObjectStore.java @@ -28,7 +28,7 @@ package org.hisp.dhis.common.hibernate; import javax.annotation.Nonnull; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.ObjectDeletionRequestedEvent; import org.hisp.dhis.common.SoftDeletableObject; import org.hisp.dhis.security.acl.AclService; @@ -42,15 +42,14 @@ public class SoftDeleteHibernateObjectStore extends HibernateIdentifiableObjectStore { public SoftDeleteHibernateObjectStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, Class clazz, CurrentUserService currentUserService, AclService aclService, boolean cacheable) { - super( - sessionFactory, jdbcTemplate, publisher, clazz, currentUserService, aclService, cacheable); + super(entityManager, jdbcTemplate, publisher, clazz, currentUserService, aclService, cacheable); } @Override diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/config/StartupConfig.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/config/StartupConfig.java index b6f9f35dc659..f6492c60b2c2 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/config/StartupConfig.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/config/StartupConfig.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.config; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManagerFactory; import org.hisp.dhis.category.CategoryService; import org.hisp.dhis.configuration.ConfigurationService; import org.hisp.dhis.dataelement.DataElementDefaultDimensionPopulator; @@ -56,8 +56,8 @@ public class StartupConfig { @Bean("org.hisp.dhis.period.PeriodTypePopulator") public PeriodTypePopulator periodTypePopulator( - PeriodStore periodStore, SessionFactory sessionFactory) { - PeriodTypePopulator populator = new PeriodTypePopulator(periodStore, sessionFactory); + PeriodStore periodStore, EntityManagerFactory entityManagerFactory) { + PeriodTypePopulator populator = new PeriodTypePopulator(periodStore, entityManagerFactory); populator.setName("PeriodTypePopulator"); populator.setRunlevel(3); return populator; diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/config/StoreConfig.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/config/StoreConfig.java index 9dda93c7cdf8..f4e354b6e58d 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/config/StoreConfig.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/config/StoreConfig.java @@ -27,7 +27,8 @@ */ package org.hisp.dhis.config; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.common.hibernate.HibernateAnalyticalObjectStore; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.constant.Constant; @@ -64,7 +65,8 @@ */ @Configuration("coreStoreConfig") public class StoreConfig { - @Autowired private SessionFactory sessionFactory; + + @PersistenceContext private EntityManager entityManager; @Autowired private JdbcTemplate jdbcTemplate; @@ -77,7 +79,7 @@ public class StoreConfig { @Bean("org.hisp.dhis.indicator.IndicatorTypeStore") public HibernateIdentifiableObjectStore indicatorTypeStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, IndicatorType.class, @@ -89,7 +91,7 @@ public HibernateIdentifiableObjectStore indicatorTypeStore() { @Bean("org.hisp.dhis.indicator.IndicatorGroupStore") public HibernateIdentifiableObjectStore indicatorGroupStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, IndicatorGroup.class, @@ -101,7 +103,7 @@ public HibernateIdentifiableObjectStore indicatorGroupStore() { @Bean("org.hisp.dhis.indicator.IndicatorGroupSetStore") public HibernateIdentifiableObjectStore indicatorGroupSetStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, IndicatorGroupSet.class, @@ -113,7 +115,7 @@ public HibernateIdentifiableObjectStore indicatorGroupSetStor @Bean("org.hisp.dhis.predictor.PredictorGroupStore") public HibernateIdentifiableObjectStore predictorGroupStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, PredictorGroup.class, @@ -125,31 +127,31 @@ public HibernateIdentifiableObjectStore predictorGroupStore() { @Bean("org.hisp.dhis.expression.ExpressionStore") public HibernateGenericStore expressionStore() { return new HibernateGenericStore<>( - sessionFactory, jdbcTemplate, publisher, Expression.class, true); + entityManager, jdbcTemplate, publisher, Expression.class, true); } @Bean("org.hisp.dhis.expression.ExpressionDimensionItemStore") public HibernateGenericStore expressionDimensionItemStore() { return new HibernateGenericStore<>( - sessionFactory, jdbcTemplate, publisher, ExpressionDimensionItem.class, true); + entityManager, jdbcTemplate, publisher, ExpressionDimensionItem.class, true); } @Bean("org.hisp.dhis.user.UserGroupAccessStore") public HibernateGenericStore userGroupAccessStore() { return new HibernateGenericStore<>( - sessionFactory, jdbcTemplate, publisher, UserGroupAccess.class, true); + entityManager, jdbcTemplate, publisher, UserGroupAccess.class, true); } @Bean("org.hisp.dhis.user.UserAccessStore") public HibernateGenericStore userAccessStore() { return new HibernateGenericStore<>( - sessionFactory, jdbcTemplate, publisher, UserAccess.class, true); + entityManager, jdbcTemplate, publisher, UserAccess.class, true); } @Bean("org.hisp.dhis.configuration.ConfigurationStore") public HibernateGenericStore configurationStore() { return new HibernateGenericStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, org.hisp.dhis.configuration.Configuration.class, @@ -159,7 +161,7 @@ public HibernateGenericStore configur @Bean("org.hisp.dhis.constant.ConstantStore") public HibernateIdentifiableObjectStore constantStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, Constant.class, @@ -171,7 +173,7 @@ public HibernateIdentifiableObjectStore constantStore() { @Bean("org.hisp.dhis.option.OptionSetStore") public HibernateIdentifiableObjectStore optionSetStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, OptionSet.class, @@ -183,7 +185,7 @@ public HibernateIdentifiableObjectStore optionSetStore() { @Bean("org.hisp.dhis.legend.LegendSetStore") public HibernateIdentifiableObjectStore legendSetStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, LegendSet.class, @@ -195,7 +197,7 @@ public HibernateIdentifiableObjectStore legendSetStore() { @Bean("org.hisp.dhis.program.ProgramIndicatorGroupStore") public HibernateIdentifiableObjectStore programIndicatorGroupStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, ProgramIndicatorGroup.class, @@ -207,19 +209,13 @@ public HibernateIdentifiableObjectStore programIndicatorG @Bean("org.hisp.dhis.report.ReportStore") public HibernateIdentifiableObjectStore reportStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, - jdbcTemplate, - publisher, - Report.class, - currentUserService, - aclService, - true); + entityManager, jdbcTemplate, publisher, Report.class, currentUserService, aclService, true); } @Bean("org.hisp.dhis.visualization.generic.VisualizationStore") public HibernateAnalyticalObjectStore visuzliationStore() { return new HibernateAnalyticalObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, Visualization.class, @@ -231,7 +227,7 @@ public HibernateAnalyticalObjectStore visuzliationStore() { @Bean("org.hisp.dhis.dashboard.DashboardStore") public HibernateIdentifiableObjectStore dashboardStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, Dashboard.class, @@ -243,7 +239,7 @@ public HibernateIdentifiableObjectStore dashboardStore() { @Bean("org.hisp.dhis.program.ProgramExpressionStore") public HibernateGenericStore programExpressionStore() { return new HibernateGenericStore<>( - sessionFactory, jdbcTemplate, publisher, ProgramExpression.class, true); + entityManager, jdbcTemplate, publisher, ProgramExpression.class, true); } /** @@ -253,7 +249,7 @@ public HibernateGenericStore programExpressionStore() { @Bean("org.hisp.dhis.eventreport.EventReportStore") public HibernateAnalyticalObjectStore eventReportStore() { return new HibernateAnalyticalObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, EventReport.class, @@ -269,7 +265,7 @@ public HibernateAnalyticalObjectStore eventReportStore() { @Bean("org.hisp.dhis.eventchart.EventChartStore") public HibernateAnalyticalObjectStore eventChartStore() { return new HibernateAnalyticalObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, EventChart.class, @@ -281,7 +277,7 @@ public HibernateAnalyticalObjectStore eventChartStore() { @Bean("org.hisp.dhis.program.notification.ProgramNotificationStore") public HibernateIdentifiableObjectStore programNotificationStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, ProgramNotificationTemplate.class, @@ -294,7 +290,7 @@ public HibernateIdentifiableObjectStore programNoti public HibernateIdentifiableObjectStore programNotificationInstanceStore() { return new HibernateIdentifiableObjectStore<>( - sessionFactory, + entityManager, jdbcTemplate, publisher, ProgramNotificationInstance.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dashboard/hibernate/HibernateDashboardItemStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dashboard/hibernate/HibernateDashboardItemStore.java index 952aa22d0293..060c600a93c5 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dashboard/hibernate/HibernateDashboardItemStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dashboard/hibernate/HibernateDashboardItemStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.dashboard.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dashboard.Dashboard; @@ -56,13 +56,13 @@ public class HibernateDashboardItemStore extends HibernateIdentifiableObjectStore implements DashboardItemStore { public HibernateDashboardItemStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DashboardItem.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataapproval/hibernate/HibernateDataApprovalAuditStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataapproval/hibernate/HibernateDataApprovalAuditStore.java index c66ed3789baa..48e4e053af81 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataapproval/hibernate/HibernateDataApprovalAuditStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataapproval/hibernate/HibernateDataApprovalAuditStore.java @@ -34,8 +34,8 @@ import java.util.List; import java.util.Set; +import javax.persistence.EntityManager; import org.apache.commons.collections4.CollectionUtils; -import org.hibernate.SessionFactory; import org.hisp.dhis.commons.util.SqlHelper; import org.hisp.dhis.commons.util.TextUtils; import org.hisp.dhis.dataapproval.DataApprovalAudit; @@ -61,11 +61,11 @@ public class HibernateDataApprovalAuditStore extends HibernateGenericStore implements DataApprovalLevelStore { public HibernateDataApprovalLevelStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataApprovalLevel.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataapproval/hibernate/HibernateDataApprovalStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataapproval/hibernate/HibernateDataApprovalStore.java index ccac85ed7dfa..36a3535dc2cf 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataapproval/hibernate/HibernateDataApprovalStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataapproval/hibernate/HibernateDataApprovalStore.java @@ -42,11 +42,11 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.hibernate.SessionFactory; import org.hisp.dhis.cache.Cache; import org.hisp.dhis.cache.CacheProvider; import org.hisp.dhis.category.CategoryCombo; @@ -113,7 +113,7 @@ public class HibernateDataApprovalStore extends HibernateGenericStore implements DataApprovalWorkflowStore { public HibernateDataApprovalWorkflowStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataApprovalWorkflow.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementGroupSetStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementGroupSetStore.java index efa58180af31..b8f987cc0ca7 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementGroupSetStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementGroupSetStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.dataelement.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dataelement.DataElementGroupSet; import org.hisp.dhis.dataelement.DataElementGroupSetStore; @@ -42,13 +42,13 @@ public class HibernateDataElementGroupSetStore extends HibernateIdentifiableObjectStore implements DataElementGroupSetStore { public HibernateDataElementGroupSetStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataElementGroupSet.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementGroupStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementGroupStore.java index a4e9ee52c0fd..dcc677d6aabf 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementGroupStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementGroupStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.dataelement.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dataelement.DataElementGroup; import org.hisp.dhis.dataelement.DataElementGroupStore; @@ -41,13 +41,13 @@ public class HibernateDataElementGroupStore extends HibernateIdentifiableObjectStore implements DataElementGroupStore { public HibernateDataElementGroupStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataElementGroup.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementOperandStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementOperandStore.java index c7da4a0d8e9f..60b9d7557ac7 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementOperandStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementOperandStore.java @@ -29,7 +29,7 @@ import java.util.List; import javax.annotation.Nonnull; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dataelement.DataElementOperand; import org.hisp.dhis.dataelement.DataElementOperandStore; @@ -47,13 +47,13 @@ public class HibernateDataElementOperandStore extends HibernateIdentifiableObjectStore implements DataElementOperandStore { public HibernateDataElementOperandStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataElementOperand.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementStore.java index b40954aa80ae..879205cee48a 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/hibernate/HibernateDataElementStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.dataelement.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.common.ValueType; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; @@ -51,13 +51,13 @@ public class HibernateDataElementStore extends HibernateIdentifiableObjectStore implements DataElementStore { public HibernateDataElementStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataElement.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataentryform/hibernate/HibernateDataEntryFormStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataentryform/hibernate/HibernateDataEntryFormStore.java index f99d244a993f..d5a760fce9e6 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataentryform/hibernate/HibernateDataEntryFormStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataentryform/hibernate/HibernateDataEntryFormStore.java @@ -27,8 +27,8 @@ */ package org.hisp.dhis.dataentryform.hibernate; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dataentryform.DataEntryForm; import org.hisp.dhis.dataentryform.DataEntryFormStore; @@ -46,13 +46,13 @@ public class HibernateDataEntryFormStore extends HibernateIdentifiableObjectStore implements DataEntryFormStore { public HibernateDataEntryFormStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataEntryForm.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataexchange/aggregate/hibernate/HibernateAggregateDataExchangeStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataexchange/aggregate/hibernate/HibernateAggregateDataExchangeStore.java index ddcea3668792..5b79d210c7bd 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataexchange/aggregate/hibernate/HibernateAggregateDataExchangeStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataexchange/aggregate/hibernate/HibernateAggregateDataExchangeStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.dataexchange.aggregate.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dataexchange.aggregate.AggregateDataExchange; import org.hisp.dhis.dataexchange.aggregate.AggregateDataExchangeStore; @@ -42,13 +42,13 @@ public class HibernateAggregateDataExchangeStore extends HibernateIdentifiableObjectStore implements AggregateDataExchangeStore { public HibernateAggregateDataExchangeStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, AggregateDataExchange.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateCompleteDataSetRegistrationStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateCompleteDataSetRegistrationStore.java index 5700b532520f..460e4eb2117a 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateCompleteDataSetRegistrationStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateCompleteDataSetRegistrationStore.java @@ -31,10 +31,10 @@ import java.util.Date; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.CategoryOptionCombo; import org.hisp.dhis.dataset.CompleteDataSetRegistration; import org.hisp.dhis.dataset.CompleteDataSetRegistrationStore; @@ -57,11 +57,11 @@ public class HibernateCompleteDataSetRegistrationStore private final PeriodStore periodStore; public HibernateCompleteDataSetRegistrationStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, PeriodStore periodStore) { - super(sessionFactory, jdbcTemplate, publisher, CompleteDataSetRegistration.class, false); + super(entityManager, jdbcTemplate, publisher, CompleteDataSetRegistration.class, false); checkNotNull(periodStore); diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateDataSetStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateDataSetStore.java index df18b9d6246d..6523eb23250e 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateDataSetStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateDataSetStore.java @@ -32,8 +32,8 @@ import com.google.common.collect.Lists; import java.util.List; import javax.annotation.Nonnull; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dataentryform.DataEntryForm; @@ -61,14 +61,14 @@ public class HibernateDataSetStore extends HibernateIdentifiableObjectStore implements SectionStore { public HibernateSectionStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, Section.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/notifications/HibernateDataSetNotificationTemplateStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/notifications/HibernateDataSetNotificationTemplateStore.java index 204c2cdc02f0..b0a7d5c86248 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/notifications/HibernateDataSetNotificationTemplateStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/notifications/HibernateDataSetNotificationTemplateStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.dataset.notifications; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.program.notification.NotificationTrigger; @@ -45,13 +45,13 @@ public class HibernateDataSetNotificationTemplateStore extends HibernateIdentifiableObjectStore implements DataSetNotificationTemplateStore { public HibernateDataSetNotificationTemplateStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataSetNotificationTemplate.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datastore/hibernate/HibernateDatastoreStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datastore/hibernate/HibernateDatastoreStore.java index d60aecef6bbb..41481e528925 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datastore/hibernate/HibernateDatastoreStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datastore/hibernate/HibernateDatastoreStore.java @@ -36,8 +36,8 @@ import java.util.List; import java.util.function.Function; import java.util.stream.Stream; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.datastore.DatastoreEntry; @@ -58,13 +58,13 @@ public class HibernateDatastoreStore extends HibernateIdentifiableObjectStore implements DatastoreStore { public HibernateDatastoreStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DatastoreEntry.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datavalue/hibernate/HibernateDataValueAuditStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datavalue/hibernate/HibernateDataValueAuditStore.java index 4780ae84c034..5f2336f0623b 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datavalue/hibernate/HibernateDataValueAuditStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datavalue/hibernate/HibernateDataValueAuditStore.java @@ -32,10 +32,10 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Function; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.hibernate.SessionFactory; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.datavalue.DataValueAudit; import org.hisp.dhis.datavalue.DataValueAuditQueryParams; @@ -64,11 +64,11 @@ public class HibernateDataValueAuditStore extends HibernateGenericStore private static final String LAST_UPATED = "lastUpdated"; public HibernateDataValueStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, PeriodStore periodStore, StatementBuilder statementBuilder) { - super(sessionFactory, jdbcTemplate, publisher, DataValue.class, false); + super(entityManager, jdbcTemplate, publisher, DataValue.class, false); this.periodStore = periodStore; this.statementBuilder = statementBuilder; } diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/deduplication/hibernate/HibernatePotentialDuplicateStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/deduplication/hibernate/HibernatePotentialDuplicateStore.java index cccd4ae1a7e2..553891bc09a9 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/deduplication/hibernate/HibernatePotentialDuplicateStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/deduplication/hibernate/HibernatePotentialDuplicateStore.java @@ -42,12 +42,12 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.hibernate.SessionFactory; import org.hibernate.query.NativeQuery; import org.hisp.dhis.artemis.audit.Audit; import org.hisp.dhis.artemis.audit.AuditManager; @@ -92,7 +92,7 @@ public class HibernatePotentialDuplicateStore private final DhisConfigurationProvider config; public HibernatePotentialDuplicateStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, @@ -102,7 +102,7 @@ public HibernatePotentialDuplicateStore( TrackedEntityAttributeValueAuditStore trackedEntityAttributeValueAuditStore, DhisConfigurationProvider config) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, PotentialDuplicate.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/deletedobject/hibernate/HibernateDeletedObjectStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/deletedobject/hibernate/HibernateDeletedObjectStore.java index 2754b3c2763b..2fd11469a6c6 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/deletedobject/hibernate/HibernateDeletedObjectStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/deletedobject/hibernate/HibernateDeletedObjectStore.java @@ -28,12 +28,12 @@ package org.hisp.dhis.deletedobject.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.common.Pager; import org.hisp.dhis.deletedobject.DeletedObject; @@ -46,10 +46,10 @@ */ @Repository("org.hisp.dhis.deletedobject.DeletedObjectStore") public class HibernateDeletedObjectStore implements DeletedObjectStore { - private SessionFactory sessionFactory; + private EntityManager entityManager; - public HibernateDeletedObjectStore(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; + public HibernateDeletedObjectStore(EntityManager entityManager) { + this.entityManager = entityManager; } @Override @@ -174,6 +174,6 @@ private Predicate buildCriteria( } private Session getCurrentSession() { - return sessionFactory.getCurrentSession(); + return entityManager.unwrap(Session.class); } } diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/eventhook/hibernate/HibernateEventHookStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/eventhook/hibernate/HibernateEventHookStore.java index 5d6aea8b4f73..a7b69ebff6db 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/eventhook/hibernate/HibernateEventHookStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/eventhook/hibernate/HibernateEventHookStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.eventhook.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.eventhook.EventHook; import org.hisp.dhis.eventhook.EventHookStore; @@ -44,13 +44,13 @@ public class HibernateEventHookStore extends HibernateIdentifiableObjectStore implements EventHookStore { public HibernateEventHookStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, EventHook.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/eventvisualization/hibernate/HibernateEventVisualizationStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/eventvisualization/hibernate/HibernateEventVisualizationStore.java index f878298011fe..3abecc48299b 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/eventvisualization/hibernate/HibernateEventVisualizationStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/eventvisualization/hibernate/HibernateEventVisualizationStore.java @@ -36,10 +36,10 @@ import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateAnalyticalObjectStore; import org.hisp.dhis.eventvisualization.EventVisualization; import org.hisp.dhis.eventvisualization.EventVisualizationStore; @@ -66,13 +66,13 @@ private enum EventVisualizationSet { } public HibernateEventVisualizationStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, EventVisualization.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/expressiondimensionitem/hibernate/HibernateExpressionDimensionItemStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/expressiondimensionitem/hibernate/HibernateExpressionDimensionItemStore.java index 82f2adda5708..d915b01256c7 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/expressiondimensionitem/hibernate/HibernateExpressionDimensionItemStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/expressiondimensionitem/hibernate/HibernateExpressionDimensionItemStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.expressiondimensionitem.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.expressiondimensionitem.ExpressionDimensionItem; import org.hisp.dhis.security.acl.AclService; @@ -45,13 +45,13 @@ public class HibernateExpressionDimensionItemStore extends HibernateIdentifiableObjectStore { @Autowired public HibernateExpressionDimensionItemStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, ExpressionDimensionItem.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/DefaultFileResourceService.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/DefaultFileResourceService.java index 96c46639bcdc..dac3f37812ff 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/DefaultFileResourceService.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/DefaultFileResourceService.java @@ -44,8 +44,8 @@ import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.IllegalQueryException; import org.hisp.dhis.feedback.ConflictException; import org.hisp.dhis.feedback.ErrorCode; @@ -80,14 +80,14 @@ public class DefaultFileResourceService implements FileResourceService { private final PeriodService periodService; - private final SessionFactory sessionFactory; - private final FileResourceContentStore fileResourceContentStore; private final ImageProcessingService imageProcessingService; private final ApplicationEventPublisher fileEventPublisher; + private final EntityManager entityManager; + // ------------------------------------------------------------------------- // FileResourceService implementation // ------------------------------------------------------------------------- @@ -178,7 +178,7 @@ public void saveFileResource(FileResource fileResource, File file) { fileResource.setStorageStatus(FileResourceStorageStatus.PENDING); fileResourceStore.save(fileResource); - sessionFactory.getCurrentSession().flush(); + entityManager.flush(); if (FileResource.isImage(fileResource.getContentType()) && FileResourceDomain.isDomainForMultipleImages(fileResource.getDomain())) { @@ -197,7 +197,7 @@ public void saveFileResource(FileResource fileResource, File file) { public String saveFileResource(FileResource fileResource, byte[] bytes) { fileResource.setStorageStatus(FileResourceStorageStatus.PENDING); fileResourceStore.save(fileResource); - sessionFactory.getCurrentSession().flush(); + entityManager.flush(); final String uid = fileResource.getUid(); diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/hibernate/HibernateExternalFileResourceStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/hibernate/HibernateExternalFileResourceStore.java index 98512588b83f..60b728a8908d 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/hibernate/HibernateExternalFileResourceStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/hibernate/HibernateExternalFileResourceStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.fileresource.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.fileresource.ExternalFileResource; import org.hisp.dhis.fileresource.ExternalFileResourceStore; @@ -45,13 +45,13 @@ public class HibernateExternalFileResourceStore extends HibernateIdentifiableObjectStore implements ExternalFileResourceStore { public HibernateExternalFileResourceStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, ExternalFileResource.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/hibernate/HibernateFileResourceStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/hibernate/HibernateFileResourceStore.java index bcb8461a471d..ac97dc104893 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/hibernate/HibernateFileResourceStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/fileresource/hibernate/HibernateFileResourceStore.java @@ -33,7 +33,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.datavalue.DataValueKey; import org.hisp.dhis.fileresource.FileResource; @@ -53,13 +53,13 @@ public class HibernateFileResourceStore extends HibernateIdentifiableObjectStore Set.of("image/jpg", "image/png", "image/jpeg"); public HibernateFileResourceStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, FileResource.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/gist/DefaultGistService.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/gist/DefaultGistService.java index af75ef8e4644..ce666a68775a 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/gist/DefaultGistService.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/gist/DefaultGistService.java @@ -38,9 +38,9 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.attribute.Attribute; import org.hisp.dhis.attribute.AttributeService; @@ -66,7 +66,7 @@ public class DefaultGistService implements GistService, GistBuilder.GistBuilderS */ private static final String NOW_PARAMETER_VALUE = "now"; - private final SessionFactory sessionFactory; + private final EntityManager entityManager; private final SchemaService schemaService; @@ -81,7 +81,7 @@ public class DefaultGistService implements GistService, GistBuilder.GistBuilderS private final ObjectMapper jsonMapper; private Session getSession() { - return sessionFactory.getCurrentSession(); + return entityManager.unwrap(Session.class); } @Override diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/i18n/hibernate/HibernateI18nLocaleStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/i18n/hibernate/HibernateI18nLocaleStore.java index 3c44a5067b51..d0e6acbe1044 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/i18n/hibernate/HibernateI18nLocaleStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/i18n/hibernate/HibernateI18nLocaleStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.i18n.hibernate; import java.util.Locale; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.i18n.I18nLocaleStore; import org.hisp.dhis.i18n.locale.I18nLocale; @@ -43,13 +43,13 @@ public class HibernateI18nLocaleStore extends HibernateIdentifiableObjectStore implements I18nLocaleStore { public HibernateI18nLocaleStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, I18nLocale.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/indicator/hibernate/HibernateIndicatorStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/indicator/hibernate/HibernateIndicatorStore.java index 71cccf00e871..606b72c4d247 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/indicator/hibernate/HibernateIndicatorStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/indicator/hibernate/HibernateIndicatorStore.java @@ -28,7 +28,7 @@ package org.hisp.dhis.indicator.hibernate; import java.util.List; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.indicator.IndicatorStore; @@ -45,13 +45,13 @@ public class HibernateIndicatorStore extends HibernateIdentifiableObjectStore implements IndicatorStore { public HibernateIndicatorStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, Indicator.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/interpretation/hibernate/HibernateInterpretationStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/interpretation/hibernate/HibernateInterpretationStore.java index 9dadb4ee1a58..311013310d89 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/interpretation/hibernate/HibernateInterpretationStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/interpretation/hibernate/HibernateInterpretationStore.java @@ -28,7 +28,7 @@ package org.hisp.dhis.interpretation.hibernate; import java.util.List; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.eventvisualization.EventVisualization; import org.hisp.dhis.interpretation.Interpretation; @@ -50,13 +50,13 @@ public class HibernateInterpretationStore extends HibernateIdentifiableObjectSto implements InterpretationStore { @Autowired public HibernateInterpretationStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, Interpretation.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateExternalMapLayerStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateExternalMapLayerStore.java index 8e6653c7a3e9..738a162098cc 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateExternalMapLayerStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateExternalMapLayerStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.mapping.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.mapping.ExternalMapLayer; import org.hisp.dhis.mapping.ExternalMapLayerStore; @@ -44,13 +44,13 @@ public class HibernateExternalMapLayerStore extends HibernateIdentifiableObjectStore implements ExternalMapLayerStore { public HibernateExternalMapLayerStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, ExternalMapLayer.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateMapStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateMapStore.java index 99709f2c5b60..b086fedab720 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateMapStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateMapStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.mapping.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hibernate.query.Query; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.mapping.Map; @@ -45,12 +45,12 @@ @Repository("org.hisp.dhis.mapping.MapStore") public class HibernateMapStore extends HibernateIdentifiableObjectStore implements MapStore { public HibernateMapStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { - super(sessionFactory, jdbcTemplate, publisher, Map.class, currentUserService, aclService, true); + super(entityManager, jdbcTemplate, publisher, Map.class, currentUserService, aclService, true); } @Override diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateMapViewStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateMapViewStore.java index b17deb41c1b3..e668ad7ad9fe 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateMapViewStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/hibernate/HibernateMapViewStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.mapping.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateAnalyticalObjectStore; import org.hisp.dhis.mapping.MapView; import org.hisp.dhis.mapping.MapViewStore; @@ -47,13 +47,13 @@ public class HibernateMapViewStore extends HibernateAnalyticalObjectStore implements MapViewStore { public HibernateMapViewStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, MapView.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/message/hibernate/HibernateMessageConversationStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/message/hibernate/HibernateMessageConversationStore.java index f9077932828e..2fb7be4f91ae 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/message/hibernate/HibernateMessageConversationStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/message/hibernate/HibernateMessageConversationStore.java @@ -32,7 +32,7 @@ import java.util.Collection; import java.util.List; import java.util.stream.Collectors; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hibernate.query.Query; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.jdbc.StatementBuilder; @@ -62,14 +62,14 @@ public class HibernateMessageConversationStore private final StatementBuilder statementBuilder; public HibernateMessageConversationStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService, StatementBuilder statementBuilder) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, MessageConversation.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/metadata/version/hibernate/HibernateMetadataVersionStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/metadata/version/hibernate/HibernateMetadataVersionStore.java index 48813b507320..1df0fa12b39a 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/metadata/version/hibernate/HibernateMetadataVersionStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/metadata/version/hibernate/HibernateMetadataVersionStore.java @@ -29,8 +29,8 @@ import java.util.Date; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.metadata.version.MetadataVersion; import org.hisp.dhis.metadata.version.MetadataVersionStore; @@ -49,13 +49,13 @@ public class HibernateMetadataVersionStore extends HibernateIdentifiableObjectStore implements MetadataVersionStore { public HibernateMetadataVersionStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, MetadataVersion.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/note/hibernate/HibernateNoteStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/note/hibernate/HibernateNoteStore.java index 4ac8f2ecc8ab..f8443ef0c793 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/note/hibernate/HibernateNoteStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/note/hibernate/HibernateNoteStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.note.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.note.Note; import org.hisp.dhis.note.NoteStore; @@ -44,20 +44,19 @@ public class HibernateNoteStore extends HibernateIdentifiableObjectStore implements NoteStore { public HibernateNoteStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, jdbcTemplate, publisher, Note.class, currentUserService, aclService, false); + entityManager, jdbcTemplate, publisher, Note.class, currentUserService, aclService, false); } @Override public boolean exists(String uid) { return (boolean) - sessionFactory - .getCurrentSession() + entityManager .createNativeQuery("select exists(select 1 from note where uid=:uid)") .setParameter("uid", uid) .getSingleResult(); diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/notification/logging/HibernateNotificationLoggingStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/notification/logging/HibernateNotificationLoggingStore.java index 58aecc0f97bf..9da7af30761c 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/notification/logging/HibernateNotificationLoggingStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/notification/logging/HibernateNotificationLoggingStore.java @@ -27,8 +27,8 @@ */ package org.hisp.dhis.notification.logging; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.security.acl.AclService; import org.hisp.dhis.user.CurrentUserService; @@ -42,13 +42,13 @@ public class HibernateNotificationLoggingStore extends HibernateIdentifiableObjectStore implements NotificationLoggingStore { public HibernateNotificationLoggingStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, ExternalNotificationLogEntry.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionGroupSetStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionGroupSetStore.java index ed1f89fc0ff9..4790bab80dbb 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionGroupSetStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionGroupSetStore.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.option.hibernate; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.option.OptionGroupSet; import org.hisp.dhis.option.OptionGroupSetStore; @@ -44,13 +44,13 @@ public class HibernateOptionGroupSetStore extends HibernateIdentifiableObjectStore implements OptionGroupSetStore { public HibernateOptionGroupSetStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, OptionGroupSet.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionGroupStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionGroupStore.java index eecf340d57bb..a73791db6624 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionGroupStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionGroupStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.option.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.DataDimensionType; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.option.OptionGroup; @@ -48,13 +48,13 @@ public class HibernateOptionGroupStore extends HibernateIdentifiableObjectStore implements OptionGroupStore { public HibernateOptionGroupStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, OptionGroup.class, diff --git a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionStore.java b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionStore.java index ee0f2a6f3104..515f2ebf8bec 100644 --- a/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionStore.java +++ b/dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/option/hibernate/HibernateOptionStore.java @@ -28,7 +28,7 @@ package org.hisp.dhis.option.hibernate; import java.util.List; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hibernate.query.Query; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.option.Option; @@ -46,19 +46,13 @@ public class HibernateOptionStore extends HibernateIdentifiableObjectStore + + javax.persistence + javax.persistence-api + com.google.code.gson gson diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/AdxPipedImporter.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/AdxPipedImporter.java index f7818ba9c9cd..f08987c94871 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/AdxPipedImporter.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/AdxPipedImporter.java @@ -31,7 +31,7 @@ import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.concurrent.Callable; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManagerFactory; import org.hisp.dhis.commons.util.StreamUtils; import org.hisp.dhis.dbms.DbmsUtils; import org.hisp.dhis.dxf2.common.ImportOptions; @@ -57,7 +57,7 @@ public class AdxPipedImporter implements Callable { private final JobConfiguration id; - private final SessionFactory sessionFactory; + private final EntityManagerFactory entityManagerFactory; private final Authentication authentication; @@ -66,20 +66,20 @@ public AdxPipedImporter( ImportOptions importOptions, JobConfiguration id, PipedOutputStream pipeOut, - SessionFactory sessionFactory) + EntityManagerFactory entityManagerFactory) throws IOException { this.dataValueSetService = dataValueSetService; this.pipeIn = new PipedInputStream(pipeOut, PIPE_BUFFER_SIZE); this.importOptions = importOptions; this.id = id; - this.sessionFactory = sessionFactory; + this.entityManagerFactory = entityManagerFactory; this.authentication = SecurityContextHolder.getContext().getAuthentication(); } @Override public ImportSummary call() { SecurityContextHolder.getContext().setAuthentication(authentication); - DbmsUtils.bindSessionToThread(sessionFactory); + DbmsUtils.bindSessionToThread(entityManagerFactory); try { return dataValueSetService.importDataValueSetXml(pipeIn, importOptions, id); @@ -87,7 +87,7 @@ public ImportSummary call() { return ImportSummary.error("Exception: " + ex.getMessage()); } finally { StreamUtils.closeQuietly(pipeIn); - DbmsUtils.unbindSessionFromThread(sessionFactory); + DbmsUtils.unbindSessionFromThread(entityManagerFactory); } } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/DefaultAdxDataService.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/DefaultAdxDataService.java index a199e24223ba..8c176e36d84d 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/DefaultAdxDataService.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/DefaultAdxDataService.java @@ -53,6 +53,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; +import javax.persistence.EntityManagerFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; @@ -60,7 +61,6 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.xerces.util.XMLChar; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.Category; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.category.CategoryComboMap; @@ -121,7 +121,7 @@ public class DefaultAdxDataService implements AdxDataService { private final IdentifiableObjectManager identifiableObjectManager; - private final SessionFactory sessionFactory; + private final EntityManagerFactory entityManagerFactory; private final Notifier notifier; @@ -382,7 +382,7 @@ private ImportSummary saveDataValueSetInternal( Future futureImportSummary = executor.submit( new AdxPipedImporter( - dataValueSetService, adxImportOptions, dxfJobId, pipeOut, sessionFactory)); + dataValueSetService, adxImportOptions, dxfJobId, pipeOut, entityManagerFactory)); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter dxfWriter = factory.createXMLStreamWriter(pipeOut); diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/dataset/DefaultCompleteDataSetRegistrationExchangeService.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/dataset/DefaultCompleteDataSetRegistrationExchangeService.java index a14e523ecd6b..d5b1b2b653d1 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/dataset/DefaultCompleteDataSetRegistrationExchangeService.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/dataset/DefaultCompleteDataSetRegistrationExchangeService.java @@ -244,9 +244,9 @@ public ImportSummary saveCompleteDataSetRegistrationsJson( private ImportSummary saveCompleteDataSetRegistrations( ImportOptions importOptions, Callable deserializeRegistrations) { - BatchHandler batchHandler = - batchHandlerFactory.createBatchHandler(CompleteDataSetRegistrationBatchHandler.class); - try { + + try (BatchHandler batchHandler = + batchHandlerFactory.createBatchHandler(CompleteDataSetRegistrationBatchHandler.class)) { CompleteDataSetRegistrations completeDataSetRegistrations = deserializeRegistrations.call(); ImportSummary summary = saveCompleteDataSetRegistrations( @@ -256,7 +256,7 @@ private ImportSummary saveCompleteDataSetRegistrations( return summary; } catch (Exception ex) { - batchHandler.flush(); + log.error("Complete data set registrations could not be saved."); return handleImportError(ex); } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java index d338bd8b2e99..df29650af7d3 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java @@ -620,14 +620,13 @@ private ImportSummary importDataValueSet( ImportOptions options, JobConfiguration id, Callable createReader) { options = ObjectUtils.firstNonNull(options, ImportOptions.getDefaultImportOptions()); - BatchHandler dvBatch = - batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class); - BatchHandler dvaBatch = - batchHandlerFactory.createBatchHandler(DataValueAuditBatchHandler.class); - notifier.clear(id); - try (DataValueSetReader reader = createReader.call()) { + try (BatchHandler dvBatch = + batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class); + BatchHandler dvaBatch = + batchHandlerFactory.createBatchHandler(DataValueAuditBatchHandler.class); + DataValueSetReader reader = createReader.call()) { ImportSummary summary = importDataValueSet(options, id, reader, dvBatch, dvaBatch); dvBatch.flush(); @@ -640,8 +639,6 @@ private ImportSummary importDataValueSet( return summary; } catch (Exception ex) { - dvBatch.flush(); - dvaBatch.flush(); log.error(DebugUtils.getStackTrace(ex)); notifier.notify(id, ERROR, "Process failed: " + ex.getMessage(), true); return new ImportSummary(ImportStatus.ERROR, "The import process failed: " + ex.getMessage()); diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/event/ImportEventsTask.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/event/ImportEventsTask.java index 4286889ebff6..b6b973bd44bf 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/event/ImportEventsTask.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/event/ImportEventsTask.java @@ -28,7 +28,7 @@ package org.hisp.dhis.dxf2.deprecated.tracker.event; import java.util.List; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManagerFactory; import org.hisp.dhis.dbms.DbmsUtils; import org.hisp.dhis.dxf2.common.ImportOptions; import org.hisp.dhis.scheduling.JobConfiguration; @@ -46,20 +46,20 @@ public class ImportEventsTask extends SecurityContextRunnable { private final JobConfiguration id; - private final SessionFactory sessionFactory; + private final EntityManagerFactory entityManagerFactory; public ImportEventsTask( List events, EventService eventService, ImportOptions importOptions, JobConfiguration id, - SessionFactory sessionFactory) { + EntityManagerFactory entityManagerFactory) { super(); this.events = events; this.eventService = eventService; this.importOptions = importOptions; this.id = id; - this.sessionFactory = sessionFactory; + this.entityManagerFactory = entityManagerFactory; } @Override @@ -69,11 +69,11 @@ public void call() { @Override public void before() { - DbmsUtils.bindSessionToThread(sessionFactory); + DbmsUtils.bindSessionToThread(entityManagerFactory); } @Override public void after() { - DbmsUtils.unbindSessionFromThread(sessionFactory); + DbmsUtils.unbindSessionFromThread(entityManagerFactory); } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/event/JdbcEventStore.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/event/JdbcEventStore.java index 92547a225d9c..58a7ad772d75 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/event/JdbcEventStore.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/event/JdbcEventStore.java @@ -1052,7 +1052,7 @@ private String getEventSelectQuery( return selectBuilder .append( - "pi.uid as pi_uid, pi.status as pi_status, pi.followup as pi_followup, pi.enrollmentdate as pi_enrollmentdate, pi.incidentdate as pi_incidentdate, ") + "pi.uid as pi_uid, pi.status as pi_status, pi.followup as pi_followup, pi.enrollmentdate as pi_enrollmentdate, pi.occurreddate as pi_incidentdate, ") .append("p.type as p_type, ps.uid as ps_uid, ou.name as ou_name, ") .append( "tei.trackedentityid as tei_id, tei.uid as tei_uid, teiou.uid as tei_ou, teiou.name as tei_ou_name, tei.created as tei_created, tei.inactive as tei_inactive ") @@ -1171,13 +1171,13 @@ private StringBuilder getFromWhereClause( "enrollmentOccurredBefore", params.getEnrollmentOccurredBefore(), Types.TIMESTAMP); fromBuilder .append(hlp.whereAnd()) - .append(" (pi.incidentdate <= :enrollmentOccurredBefore ) "); + .append(" (pi.occurreddate <= :enrollmentOccurredBefore ) "); } if (params.getEnrollmentOccurredAfter() != null) { mapSqlParameterSource.addValue( "enrollmentOccurredAfter", params.getEnrollmentOccurredAfter(), Types.TIMESTAMP); - fromBuilder.append(hlp.whereAnd()).append(" (pi.incidentdate >= :enrollmentOccurredAfter ) "); + fromBuilder.append(hlp.whereAnd()).append(" (pi.occurreddate >= :enrollmentOccurredAfter ) "); } if (params.getDueDateStart() != null) { diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/importer/context/WorkContextLoader.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/importer/context/WorkContextLoader.java index 4b45b67a8943..e098c34ee89a 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/importer/context/WorkContextLoader.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/importer/context/WorkContextLoader.java @@ -29,9 +29,9 @@ import java.util.List; import java.util.Map; +import javax.persistence.EntityManager; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; -import org.hibernate.SessionFactory; import org.hisp.dhis.dxf2.common.ImportOptions; import org.hisp.dhis.hibernate.HibernateProxyUtils; import org.hisp.dhis.organisationunit.OrganisationUnit; @@ -71,7 +71,7 @@ public class WorkContextLoader { private static final UidGenerator uidGen = new UidGenerator(); - private final SessionFactory sessionFactory; + private final EntityManager entityManager; public WorkContextLoader( ProgramSupplier programSupplier, @@ -85,7 +85,7 @@ public WorkContextLoader( AssignedUserSupplier assignedUserSupplier, ServiceDelegatorSupplier serviceDelegatorSupplier, ProgramOrgUnitSupplier programOrgUnitSupplier, - SessionFactory sessionFactory) { + EntityManager entityManager) { this.programSupplier = programSupplier; this.organisationUnitSupplier = organisationUnitSupplier; this.trackedEntityInstanceSupplier = trackedEntityInstanceSupplier; @@ -97,13 +97,13 @@ public WorkContextLoader( this.assignedUserSupplier = assignedUserSupplier; this.programOrgUnitSupplier = programOrgUnitSupplier; this.serviceDelegatorSupplier = serviceDelegatorSupplier; - this.sessionFactory = sessionFactory; + this.entityManager = entityManager; } @Transactional(readOnly = true) public WorkContext load( ImportOptions importOptions, List events) { - sessionFactory.getCurrentSession().flush(); + entityManager.flush(); ImportOptions localImportOptions = importOptions; // API allows a null Import Options diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/DefaultAclStore.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/DefaultAclStore.java index befb80cbabf5..a0da588bc1eb 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/DefaultAclStore.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/DefaultAclStore.java @@ -39,7 +39,7 @@ /** * @author Luciano Fiandesio */ -@Repository +@Repository("org.hisp.dhis.dxf2.deprecated.tracker.trackedentity.store.AclStore") public class DefaultAclStore implements AclStore { private final NamedParameterJdbcTemplate jdbcTemplate; diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/query/EnrollmentQuery.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/query/EnrollmentQuery.java index 93fc34014238..ddb153062f07 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/query/EnrollmentQuery.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/query/EnrollmentQuery.java @@ -77,7 +77,7 @@ public enum COLUMNS { .put(COLUMNS.LAST_UPDATED_BY, new TableColumn("pi", "lastupdatedbyuserinfo")) .put(COLUMNS.STATUS, new TableColumn("pi", "status")) .put(COLUMNS.ENROLLMENTDATE, new TableColumn("pi", "enrollmentdate")) - .put(COLUMNS.INCIDENTDATE, new TableColumn("pi", "incidentdate")) + .put(COLUMNS.INCIDENTDATE, new TableColumn("pi", "occurreddate")) .put(COLUMNS.FOLLOWUP, new TableColumn("pi", "followup")) .put(COLUMNS.COMPLETED, new TableColumn("pi", "completeddate")) .put(COLUMNS.COMPLETEDBY, new TableColumn("pi", "completedby")) diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/AnalyticalObjectImportHandler.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/AnalyticalObjectImportHandler.java index 7a3c1f86bc21..bc017cc85e94 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/AnalyticalObjectImportHandler.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/AnalyticalObjectImportHandler.java @@ -27,12 +27,15 @@ */ package org.hisp.dhis.dxf2.metadata; -import org.hibernate.Session; +import javax.persistence.EntityManager; import org.hisp.dhis.common.BaseAnalyticalObject; import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle; import org.hisp.dhis.schema.Schema; public interface AnalyticalObjectImportHandler { void handleAnalyticalObject( - Session session, Schema schema, BaseAnalyticalObject analyticalObject, ObjectBundle bundle); + EntityManager entityManager, + Schema schema, + BaseAnalyticalObject analyticalObject, + ObjectBundle bundle); } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/DefaultAnalyticalObjectImportHandler.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/DefaultAnalyticalObjectImportHandler.java index 6fa3240ebf06..ce360d831a8a 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/DefaultAnalyticalObjectImportHandler.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/DefaultAnalyticalObjectImportHandler.java @@ -29,8 +29,8 @@ import java.util.ArrayList; import java.util.List; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; -import org.hibernate.Session; import org.hisp.dhis.category.CategoryDimension; import org.hisp.dhis.category.CategoryOption; import org.hisp.dhis.common.BaseAnalyticalObject; @@ -55,12 +55,15 @@ public class DefaultAnalyticalObjectImportHandler implements AnalyticalObjectImp @Override public void handleAnalyticalObject( - Session session, Schema schema, BaseAnalyticalObject analyticalObject, ObjectBundle bundle) { - handleDataDimensionItems(session, schema, analyticalObject, bundle); - handleCategoryDimensions(session, schema, analyticalObject, bundle); - handleDataElementDimensions(session, schema, analyticalObject, bundle); - handleAttributeDimensions(session, schema, analyticalObject, bundle); - handleProgramIndicatorDimensions(session, schema, analyticalObject, bundle); + EntityManager entityManager, + Schema schema, + BaseAnalyticalObject analyticalObject, + ObjectBundle bundle) { + handleDataDimensionItems(entityManager, schema, analyticalObject, bundle); + handleCategoryDimensions(entityManager, schema, analyticalObject, bundle); + handleDataElementDimensions(entityManager, schema, analyticalObject, bundle); + handleAttributeDimensions(entityManager, schema, analyticalObject, bundle); + handleProgramIndicatorDimensions(entityManager, schema, analyticalObject, bundle); handleVisualizationLegendSet(schema, analyticalObject, bundle); } @@ -115,7 +118,10 @@ private void handleVisualizationLegendSet( } private void handleDataDimensionItems( - Session session, Schema schema, BaseAnalyticalObject analyticalObject, ObjectBundle bundle) { + EntityManager entityManager, + Schema schema, + BaseAnalyticalObject analyticalObject, + ObjectBundle bundle) { if (!schema.hasPersistedProperty("dataDimensionItems")) return; for (DataDimensionItem dataDimensionItem : analyticalObject.getDataDimensionItems()) { @@ -192,12 +198,15 @@ private void handleDataDimensionItems( preheatService.connectReferences( dataDimensionItem, bundle.getPreheat(), bundle.getPreheatIdentifier()); - session.save(dataDimensionItem); + entityManager.persist(dataDimensionItem); } } private void handleCategoryDimensions( - Session session, Schema schema, BaseAnalyticalObject analyticalObject, ObjectBundle bundle) { + EntityManager entityManager, + Schema schema, + BaseAnalyticalObject analyticalObject, + ObjectBundle bundle) { if (!schema.hasPersistedProperty("categoryDimensions")) return; for (CategoryDimension categoryDimension : analyticalObject.getCategoryDimensions()) { @@ -219,12 +228,15 @@ private void handleCategoryDimensions( preheatService.connectReferences( categoryDimension, bundle.getPreheat(), bundle.getPreheatIdentifier()); - session.save(categoryDimension); + entityManager.persist(categoryDimension); } } private void handleDataElementDimensions( - Session session, Schema schema, BaseAnalyticalObject analyticalObject, ObjectBundle bundle) { + EntityManager entityManager, + Schema schema, + BaseAnalyticalObject analyticalObject, + ObjectBundle bundle) { if (!schema.hasPersistedProperty("dataElementDimensions")) return; for (TrackedEntityDataElementDimension dataElementDimension : @@ -248,12 +260,15 @@ private void handleDataElementDimensions( preheatService.connectReferences( dataElementDimension, bundle.getPreheat(), bundle.getPreheatIdentifier()); - session.save(dataElementDimension); + entityManager.persist(dataElementDimension); } } private void handleAttributeDimensions( - Session session, Schema schema, BaseAnalyticalObject analyticalObject, ObjectBundle bundle) { + EntityManager entityManager, + Schema schema, + BaseAnalyticalObject analyticalObject, + ObjectBundle bundle) { if (!schema.hasPersistedProperty("attributeDimensions")) return; for (TrackedEntityAttributeDimension attributeDimension : @@ -274,12 +289,15 @@ private void handleAttributeDimensions( preheatService.connectReferences( attributeDimension, bundle.getPreheat(), bundle.getPreheatIdentifier()); - session.save(attributeDimension); + entityManager.persist(attributeDimension); } } private void handleProgramIndicatorDimensions( - Session session, Schema schema, BaseAnalyticalObject analyticalObject, ObjectBundle bundle) { + EntityManager entityManager, + Schema schema, + BaseAnalyticalObject analyticalObject, + ObjectBundle bundle) { if (!schema.hasPersistedProperty("programIndicatorDimensions")) return; for (TrackedEntityProgramIndicatorDimension programIndicatorDimension : @@ -299,7 +317,7 @@ private void handleProgramIndicatorDimensions( preheatService.connectReferences( programIndicatorDimension, bundle.getPreheat(), bundle.getPreheatIdentifier()); - session.save(programIndicatorDimension); + entityManager.persist(programIndicatorDimension); } } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/collection/DefaultCollectionService.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/collection/DefaultCollectionService.java index 7ceac287b178..42361fb1e846 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/collection/DefaultCollectionService.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/collection/DefaultCollectionService.java @@ -32,6 +32,7 @@ import java.util.Collection; import java.util.List; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.common.IdentifiableObjectManager; @@ -73,6 +74,8 @@ public class DefaultCollectionService implements CollectionService { private final SchemaValidator schemaValidator; + private final EntityManager entityManager; + @Override @Transactional public TypeReport addCollectionItems( @@ -91,7 +94,6 @@ public TypeReport addCollectionItems( } TypeReport report = new TypeReport(property.getItemKlass()); - manager.refresh(object); if (property.isOwner()) { addOwnedCollectionItems(object, property, itemCodes, report); @@ -99,7 +101,6 @@ public TypeReport addCollectionItems( addNonOwnedCollectionItems(object, property, itemCodes, report); } - dbmsManager.clearSession(); return report; } @@ -122,7 +123,6 @@ private void addOwnedCollectionItems( } }); validateAndThrowErrors(() -> schemaValidator.validateProperty(property, object)); - manager.update(object); } private void addNonOwnedCollectionItems( @@ -150,6 +150,7 @@ private void addNonOwnedCollectionItems( report.getStats().incIgnored(); } }); + entityManager.refresh(object); } @Override @@ -170,7 +171,6 @@ public TypeReport delCollectionItems( } TypeReport report = new TypeReport(property.getItemKlass()); - manager.refresh(object); if (property.isOwner()) { delOwnedCollectionItems(object, property, itemCodes, report); @@ -179,9 +179,6 @@ public TypeReport delCollectionItems( } validateAndThrowErrors(() -> schemaValidator.validateProperty(property, object)); - manager.update(object); - - dbmsManager.clearSession(); return report; } @@ -232,6 +229,7 @@ private void delNonOwnedCollectionItems( report.getStats().incIgnored(); } }); + entityManager.refresh(object); } @Override diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/DefaultObjectBundleService.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/DefaultObjectBundleService.java index f82d82ad7a53..c6cba14e4596 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/DefaultObjectBundleService.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/DefaultObjectBundleService.java @@ -37,10 +37,10 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hisp.dhis.cache.HibernateCacheManager; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.DeleteNotAllowedException; @@ -78,7 +78,7 @@ public class DefaultObjectBundleService implements ObjectBundleService { private final CurrentUserService currentUserService; private final PreheatService preheatService; private final SchemaService schemaService; - private final SessionFactory sessionFactory; + private final EntityManager entityManager; private final IdentifiableObjectManager manager; private final DbmsManager dbmsManager; private final HibernateCacheManager cacheManager; @@ -125,7 +125,7 @@ public ObjectBundleCommitReport commit(ObjectBundle bundle, JobProgress progress } List> klasses = getSortedClasses(bundle); - Session session = sessionFactory.getCurrentSession(); + Session session = entityManager.unwrap(Session.class); List> commitHooks = objectBundleHooks.getCommitHooks(klasses); commitHooks.forEach(hook -> hook.preCommit(bundle)); diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/AbstractObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/AbstractObjectBundleHook.java index e01aae6b755f..22dd325df56f 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/AbstractObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/AbstractObjectBundleHook.java @@ -29,7 +29,9 @@ import java.util.List; import java.util.function.Consumer; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import org.hibernate.Session; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle; import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundleHook; @@ -47,7 +49,7 @@ public class AbstractObjectBundleHook implements ObjectBundleHook { @Autowired protected PreheatService preheatService; - @Autowired protected SessionFactory sessionFactory; + @PersistenceContext protected EntityManager entityManager; @Autowired protected SchemaService schemaService; @@ -102,4 +104,8 @@ public void postUpdate(T persistedObject, ObjectBundle bundle) { public void preDelete(T persistedObject, ObjectBundle bundle) { // by default nothing to do } + + protected Session getSession() { + return entityManager.unwrap(Session.class); + } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/AnalyticalObjectObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/AnalyticalObjectObjectBundleHook.java index b75c717f9aab..7d0c7ea05d66 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/AnalyticalObjectObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/AnalyticalObjectObjectBundleHook.java @@ -28,7 +28,6 @@ package org.hisp.dhis.dxf2.metadata.objectbundle.hooks; import lombok.AllArgsConstructor; -import org.hibernate.Session; import org.hisp.dhis.common.AnalyticalObject; import org.hisp.dhis.common.BaseAnalyticalObject; import org.hisp.dhis.dxf2.metadata.AnalyticalObjectImportHandler; @@ -52,9 +51,9 @@ public void preCreate(AnalyticalObject object, ObjectBundle bundle) { BaseAnalyticalObject analyticalObject = (BaseAnalyticalObject) object; Schema schema = schemaService.getDynamicSchema(HibernateProxyUtils.getRealClass(analyticalObject)); - Session session = sessionFactory.getCurrentSession(); - analyticalObjectImportHandler.handleAnalyticalObject(session, schema, analyticalObject, bundle); + analyticalObjectImportHandler.handleAnalyticalObject( + entityManager, schema, analyticalObject, bundle); } @Override @@ -64,8 +63,8 @@ public void preUpdate( Schema schema = schemaService.getDynamicSchema(HibernateProxyUtils.getRealClass(analyticalObject)); - Session session = sessionFactory.getCurrentSession(); - analyticalObjectImportHandler.handleAnalyticalObject(session, schema, analyticalObject, bundle); + analyticalObjectImportHandler.handleAnalyticalObject( + entityManager, schema, analyticalObject, bundle); } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/DataInputPeriodObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/DataInputPeriodObjectBundleHook.java index 8e56506d7464..51fa29046e91 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/DataInputPeriodObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/DataInputPeriodObjectBundleHook.java @@ -57,6 +57,6 @@ private void setPeriod(DataInputPeriod dataInputPeriod) { Period period = periodService.getPeriod(dataInputPeriod.getPeriod().getIsoDate()); dataInputPeriod.setPeriod(period); - sessionFactory.getCurrentSession().save(period); + getSession().save(period); } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/DataSetObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/DataSetObjectBundleHook.java index 1b4cdb64816c..b63ff14b9d8f 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/DataSetObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/DataSetObjectBundleHook.java @@ -31,7 +31,6 @@ import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; -import org.hibernate.Session; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementOperand; @@ -94,8 +93,6 @@ private void deleteRemovedSection( DataSet persistedDataSet, DataSet importDataSet, ObjectBundle bundle) { if (!bundle.isMetadataSyncImport()) return; - Session session = sessionFactory.getCurrentSession(); - List importIds = importDataSet.getSections().stream() .map(IdentifiableObject::getUid) @@ -103,16 +100,15 @@ private void deleteRemovedSection( persistedDataSet.getSections().stream() .filter(section -> !importIds.contains(section.getUid())) - .forEach(session::delete); + .forEach(getSession()::delete); } private void deleteRemovedDataElementFromSection( DataSet persistedDataSet, DataSet importDataSet) { - Session session = sessionFactory.getCurrentSession(); persistedDataSet.getSections().stream() .peek(section -> section.setDataElements(getUpdatedDataElements(importDataSet, section))) - .forEach(session::update); + .forEach(getSession()::update); } private List getUpdatedDataElements(DataSet importDataSet, Section section) { diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/EmbeddedObjectObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/EmbeddedObjectObjectBundleHook.java index 19233ad7dd42..2f566e438357 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/EmbeddedObjectObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/EmbeddedObjectObjectBundleHook.java @@ -30,7 +30,6 @@ import java.util.Collection; import java.util.function.Consumer; import lombok.AllArgsConstructor; -import org.hibernate.Session; import org.hisp.dhis.common.BaseAnalyticalObject; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.IdentifiableObject; @@ -191,11 +190,9 @@ private void handleEmbeddedAnalyticalProperty( return; } - Session session = sessionFactory.getCurrentSession(); - Schema propertySchema = schemaService.getDynamicSchema(property.getItemKlass()); analyticalObjectImportHandler.handleAnalyticalObject( - session, propertySchema, (BaseAnalyticalObject) identifiableObject, bundle); + entityManager, propertySchema, (BaseAnalyticalObject) identifiableObject, bundle); } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/OptionSetObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/OptionSetObjectBundleHook.java index 8de8cd76fbfb..31393d0b9ad7 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/OptionSetObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/OptionSetObjectBundleHook.java @@ -58,6 +58,6 @@ private void updateOption(OptionSet optionSet) { } }); - sessionFactory.getCurrentSession().refresh(optionSet); + getSession().refresh(optionSet); } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/OrganisationUnitObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/OrganisationUnitObjectBundleHook.java index a31cb1b451b2..78245d6c75f0 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/OrganisationUnitObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/OrganisationUnitObjectBundleHook.java @@ -32,7 +32,6 @@ import java.util.Objects; import java.util.function.Consumer; import lombok.AllArgsConstructor; -import org.hibernate.Session; import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle; import org.hisp.dhis.feedback.ErrorCode; import org.hisp.dhis.feedback.ErrorReport; @@ -70,8 +69,6 @@ public void postCommit(ObjectBundle bundle) { Map> objectReferences = bundle.getObjectReferences(OrganisationUnit.class); - Session session = sessionFactory.getCurrentSession(); - for (OrganisationUnit identifiableObject : objects) { identifiableObject = bundle.getPreheat().get(bundle.getPreheatIdentifier(), identifiableObject); @@ -89,7 +86,6 @@ public void postCommit(ObjectBundle bundle) { OrganisationUnit parent = bundle.getPreheat().get(bundle.getPreheatIdentifier(), parentRef); organisationUnit.setParent(parent); - session.update(organisationUnit); } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/PredictorObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/PredictorObjectBundleHook.java index 01afd3ee8a3f..a305864f6ab6 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/PredictorObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/PredictorObjectBundleHook.java @@ -58,10 +58,10 @@ private void saveSkipTest(Predictor predictor, ObjectBundle bundle) { skipTest, bundle.getPreheat(), bundle.getPreheatIdentifier()); } - sessionFactory.getCurrentSession().save(predictor.getGenerator()); + getSession().save(predictor.getGenerator()); if (skipTest != null) { - sessionFactory.getCurrentSession().save(skipTest); + getSession().save(skipTest); } } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramRuleVariableObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramRuleVariableObjectBundleHook.java index 103921d03b3a..a7d7bbec12d8 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramRuleVariableObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramRuleVariableObjectBundleHook.java @@ -37,7 +37,6 @@ import java.util.stream.IntStream; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.hibernate.Session; import org.hibernate.query.Query; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle; @@ -142,9 +141,8 @@ private void failPrvWithSameNameAlreadyExists( private Query getProgramRuleVariableQuery( ProgramRuleVariable programRuleVariable) { - Session session = sessionFactory.getCurrentSession(); Query query = - session.createQuery(FROM_PROGRAM_RULE_VARIABLE, ProgramRuleVariable.class); + getSession().createQuery(FROM_PROGRAM_RULE_VARIABLE, ProgramRuleVariable.class); query.setParameter("name", programRuleVariable.getName()); query.setParameter("programUid", programRuleVariable.getProgram().getUid()); diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramStageObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramStageObjectBundleHook.java index d56ab5f46e91..615373928fa2 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramStageObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramStageObjectBundleHook.java @@ -31,7 +31,6 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import lombok.AllArgsConstructor; -import org.hibernate.Session; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.common.ValueType; import org.hisp.dhis.dataelement.DataElement; @@ -91,9 +90,7 @@ public void validate( @Override public void postCreate(ProgramStage programStage, ObjectBundle bundle) { - Session session = sessionFactory.getCurrentSession(); - - updateProgramStageSections(session, programStage); + updateProgramStageSections(programStage); } @Override @@ -119,7 +116,7 @@ private void deleteRemovedSection( persistedProgramStage.getProgramStageSections().removeAll(programStageSectionsToDelete); } - private void updateProgramStageSections(Session session, ProgramStage programStage) { + private void updateProgramStageSections(ProgramStage programStage) { if (programStage.getProgramStageSections().isEmpty()) { return; } @@ -132,8 +129,6 @@ private void updateProgramStageSections(Session session, ProgramStage programSta pss.setProgramStage(programStage); } }); - - session.update(programStage); } private void validateProgramStageDataElementsAcl( diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/RelationshipObjectBundleHook.java b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/RelationshipObjectBundleHook.java index 949470724ff7..e3298abfc3ba 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/RelationshipObjectBundleHook.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/RelationshipObjectBundleHook.java @@ -46,13 +46,13 @@ public class RelationshipObjectBundleHook extends AbstractObjectBundleHook void postTypeImport( dataSets.forEach( ds -> { ds.increaseVersion(); - sessionFactory.getCurrentSession().save(ds); + getSession().save(ds); }); } else if (Option.class.isAssignableFrom(klass)) { Set optionSets = new HashSet<>(); @@ -112,7 +112,7 @@ public void postTypeImport( optionSets.forEach( os -> { os.increaseVersion(); - sessionFactory.getCurrentSession().save(os); + getSession().save(os); }); } } diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramObjectBundleHookTest.java b/dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramObjectBundleHookTest.java index 1d33996fef12..ef7c5c8630cf 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramObjectBundleHookTest.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramObjectBundleHookTest.java @@ -42,7 +42,6 @@ import com.google.common.collect.Lists; import java.util.List; -import org.hibernate.SessionFactory; import org.hisp.dhis.feedback.ErrorCode; import org.hisp.dhis.feedback.ErrorReport; import org.hisp.dhis.program.Enrollment; @@ -77,8 +76,6 @@ class ProgramObjectBundleHookTest { @Mock private AclService aclService; - @Mock private SessionFactory sessionFactory; - private Program programA; @BeforeEach diff --git a/dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramRuleVariableObjectBundleHookTest.java b/dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramRuleVariableObjectBundleHookTest.java index dc688b20645d..b4fb9642a8cd 100644 --- a/dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramRuleVariableObjectBundleHookTest.java +++ b/dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/hooks/ProgramRuleVariableObjectBundleHookTest.java @@ -37,8 +37,8 @@ import java.util.Collections; import java.util.List; +import javax.persistence.EntityManager; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle; import org.hisp.dhis.feedback.ErrorReport; @@ -62,7 +62,7 @@ class ProgramRuleVariableObjectBundleHookTest { @InjectMocks private ProgramRuleVariableObjectBundleHook programRuleVariableObjectBundleHook; - @Mock private SessionFactory sessionFactory; + @Mock private EntityManager entityManager; @Mock private Session session; @@ -78,7 +78,7 @@ class ProgramRuleVariableObjectBundleHookTest { @BeforeEach public void setUp() { - when(sessionFactory.getCurrentSession()).thenReturn(session); + when(entityManager.unwrap(Session.class)).thenReturn(session); when(session.createQuery(anyString(), classArgumentCaptor.capture())).thenReturn(query); when(program.getUid()).thenReturn("uid"); } diff --git a/dhis-2/dhis-services/dhis-service-metadata-workflow/src/main/java/org/hisp/dhis/metadata/HibernateMetadataProposalStore.java b/dhis-2/dhis-services/dhis-service-metadata-workflow/src/main/java/org/hisp/dhis/metadata/HibernateMetadataProposalStore.java index ad847c3850c2..42705929ed29 100644 --- a/dhis-2/dhis-services/dhis-service-metadata-workflow/src/main/java/org/hisp/dhis/metadata/HibernateMetadataProposalStore.java +++ b/dhis-2/dhis-services/dhis-service-metadata-workflow/src/main/java/org/hisp/dhis/metadata/HibernateMetadataProposalStore.java @@ -27,9 +27,9 @@ */ package org.hisp.dhis.metadata; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; /** @@ -38,10 +38,10 @@ @Repository @RequiredArgsConstructor public class HibernateMetadataProposalStore implements MetadataProposalStore { - private final SessionFactory sessionFactory; + private final EntityManager entityManager; private Session getSession() { - return sessionFactory.getCurrentSession(); + return entityManager.unwrap(Session.class); } @Override @@ -55,7 +55,7 @@ public MetadataProposal getByUid(String uid) { @Override public void save(MetadataProposal proposal) { proposal.setAutoFields(); - getSession().save(proposal); + entityManager.persist(proposal); } @Override diff --git a/dhis-2/dhis-services/dhis-service-node/pom.xml b/dhis-2/dhis-services/dhis-service-node/pom.xml index e9f41d383a33..d411e0577b3a 100644 --- a/dhis-2/dhis-services/dhis-service-node/pom.xml +++ b/dhis-2/dhis-services/dhis-service-node/pom.xml @@ -33,6 +33,11 @@ dhis-support-system + + javax.persistence + javax.persistence-api + test + org.springframework spring-core @@ -126,11 +131,6 @@ mockito-junit-jupiter test - - org.hibernate - hibernate-core - test - diff --git a/dhis-2/dhis-services/dhis-service-node/src/test/java/org/hisp/dhis/fieldfilter/DefaultFieldFilterServiceTest.java b/dhis-2/dhis-services/dhis-service-node/src/test/java/org/hisp/dhis/fieldfilter/DefaultFieldFilterServiceTest.java index 50decef0b292..5ea59ea063a7 100644 --- a/dhis-2/dhis-services/dhis-service-node/src/test/java/org/hisp/dhis/fieldfilter/DefaultFieldFilterServiceTest.java +++ b/dhis-2/dhis-services/dhis-service-node/src/test/java/org/hisp/dhis/fieldfilter/DefaultFieldFilterServiceTest.java @@ -39,8 +39,8 @@ import java.util.List; import java.util.Set; import javax.annotation.Nonnull; +import javax.persistence.EntityManagerFactory; import org.hamcrest.Matchers; -import org.hibernate.SessionFactory; import org.hisp.dhis.attribute.AttributeService; import org.hisp.dhis.cache.CacheProvider; import org.hisp.dhis.cache.NoOpCache; @@ -75,7 +75,7 @@ */ @ExtendWith(MockitoExtension.class) class DefaultFieldFilterServiceTest { - @Mock private SessionFactory sessionFactory; + @Mock private EntityManagerFactory entityManagerFactory; @Mock private AclService aclService; @@ -97,7 +97,7 @@ public void setUp() { final SchemaService schemaService = new DefaultSchemaService( new DefaultPropertyIntrospectorService(new JacksonPropertyIntrospector()), - sessionFactory); + entityManagerFactory); CacheProvider cacheProvider = mock(CacheProvider.class); when(cacheProvider.createPropertyTransformerCache()).thenReturn(new NoOpCache<>()); diff --git a/dhis-2/dhis-services/dhis-service-node/src/test/java/org/hisp/dhis/node/transformers/PluckNodeTransformerTest.java b/dhis-2/dhis-services/dhis-service-node/src/test/java/org/hisp/dhis/node/transformers/PluckNodeTransformerTest.java index a64f429a5465..f726952e32f4 100644 --- a/dhis-2/dhis-services/dhis-service-node/src/test/java/org/hisp/dhis/node/transformers/PluckNodeTransformerTest.java +++ b/dhis-2/dhis-services/dhis-service-node/src/test/java/org/hisp/dhis/node/transformers/PluckNodeTransformerTest.java @@ -28,7 +28,7 @@ package org.hisp.dhis.node.transformers; import java.util.Collections; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManagerFactory; import org.hisp.dhis.category.Category; import org.hisp.dhis.category.CategoryOption; import org.hisp.dhis.node.Node; @@ -55,7 +55,7 @@ class PluckNodeTransformerTest { private final PluckNodeTransformer transformer = new PluckNodeTransformer(); - @Mock private SessionFactory sessionFactory; + @Mock private EntityManagerFactory entityManagerFactory; private SchemaService schemaService; @@ -66,7 +66,7 @@ public void setUp() { schemaService = new DefaultSchemaService( new DefaultPropertyIntrospectorService(new JacksonPropertyIntrospector()), - sessionFactory); + entityManagerFactory); collectionNode = new CollectionNode("organisationUnits", 2); collectionNode.setNamespace("testUrn"); diff --git a/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleActionStore.java b/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleActionStore.java index f819f74d4a64..4fcd8ab682c7 100644 --- a/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleActionStore.java +++ b/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleActionStore.java @@ -30,8 +30,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.programrule.ProgramRule; import org.hisp.dhis.programrule.ProgramRuleAction; @@ -58,13 +58,13 @@ public class HibernateProgramRuleActionStore ProgramRuleActionType.HIDEPROGRAMSTAGE, "programStage"); public HibernateProgramRuleActionStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, ProgramRuleAction.class, diff --git a/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleStore.java b/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleStore.java index 4422462b267a..d093280d2a3a 100644 --- a/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleStore.java +++ b/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleStore.java @@ -31,9 +31,9 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.program.Program; import org.hisp.dhis.programrule.*; @@ -51,13 +51,13 @@ public class HibernateProgramRuleStore extends HibernateIdentifiableObjectStore implements ProgramRuleStore { public HibernateProgramRuleStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, ProgramRule.class, diff --git a/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleVariableStore.java b/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleVariableStore.java index 8ea604981410..047ea3bcd34c 100644 --- a/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleVariableStore.java +++ b/dhis-2/dhis-services/dhis-service-program-rule/src/main/java/org/hisp/dhis/programrule/hibernate/HibernateProgramRuleVariableStore.java @@ -28,8 +28,8 @@ package org.hisp.dhis.programrule.hibernate; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.program.Program; @@ -50,13 +50,13 @@ public class HibernateProgramRuleVariableStore extends HibernateIdentifiableObjectStore implements ProgramRuleVariableStore { public HibernateProgramRuleVariableStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, ProgramRuleVariable.class, diff --git a/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/datastatistics/hibernate/HibernateDataStatisticsEventStore.java b/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/datastatistics/hibernate/HibernateDataStatisticsEventStore.java index ba443fcdb040..8aad9cf9cf0d 100644 --- a/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/datastatistics/hibernate/HibernateDataStatisticsEventStore.java +++ b/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/datastatistics/hibernate/HibernateDataStatisticsEventStore.java @@ -38,7 +38,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.analytics.SortOrder; import org.hisp.dhis.datastatistics.DataStatisticsEvent; import org.hisp.dhis.datastatistics.DataStatisticsEventStore; @@ -66,12 +66,12 @@ public class HibernateDataStatisticsEventStore extends HibernateGenericStore implements DataStatisticsStore { public HibernateDataStatisticsStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, DataStatistics.class, diff --git a/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/document/impl/HibernateDocumentStore.java b/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/document/impl/HibernateDocumentStore.java index 5126e0d18d46..5bca2b09aade 100644 --- a/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/document/impl/HibernateDocumentStore.java +++ b/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/document/impl/HibernateDocumentStore.java @@ -27,10 +27,10 @@ */ package org.hisp.dhis.document.impl; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.adapter.BaseIdentifiableObject_; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.document.Document; @@ -49,13 +49,13 @@ public class HibernateDocumentStore extends HibernateIdentifiableObjectStore implements DocumentStore { public HibernateDocumentStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { super( - sessionFactory, + entityManager, jdbcTemplate, publisher, Document.class, diff --git a/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/reporting/config/StoreConfig.java b/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/reporting/config/StoreConfig.java index 12478d57bd24..28ec8661b169 100644 --- a/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/reporting/config/StoreConfig.java +++ b/dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/reporting/config/StoreConfig.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.reporting.config; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.pushanalysis.PushAnalysis; import org.hisp.dhis.security.acl.AclService; @@ -44,13 +44,13 @@ public class StoreConfig { @Bean("org.hisp.dhis.pushanalysis.PushAnalysisStore") public HibernateIdentifiableObjectStore indicatorTypeStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService) { return new HibernateIdentifiableObjectStore( - sessionFactory, + entityManager, jdbcTemplate, publisher, PushAnalysis.class, diff --git a/dhis-2/dhis-services/dhis-service-schema/pom.xml b/dhis-2/dhis-services/dhis-service-schema/pom.xml index 054aa0af815a..ac735e5bb5d8 100644 --- a/dhis-2/dhis-services/dhis-service-schema/pom.xml +++ b/dhis-2/dhis-services/dhis-service-schema/pom.xml @@ -89,6 +89,10 @@ org.hisp.dhis dhis-support-hibernate + + javax.persistence + javax.persistence-api + diff --git a/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/DefaultPropertyIntrospectorService.java b/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/DefaultPropertyIntrospectorService.java index 291a9e2c3598..5a4d2e69e93b 100644 --- a/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/DefaultPropertyIntrospectorService.java +++ b/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/DefaultPropertyIntrospectorService.java @@ -32,8 +32,8 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import javax.persistence.EntityManagerFactory; import lombok.RequiredArgsConstructor; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.schema.introspection.GistPropertyIntrospector; import org.hisp.dhis.schema.introspection.HibernatePropertyIntrospector; @@ -58,7 +58,7 @@ public class DefaultPropertyIntrospectorService implements PropertyIntrospectorS private final PropertyIntrospector introspector; @Autowired - public DefaultPropertyIntrospectorService(SessionFactory sessionFactory) { + public DefaultPropertyIntrospectorService(EntityManagerFactory sessionFactory) { this( new HibernatePropertyIntrospector(sessionFactory) .then(new JacksonPropertyIntrospector()) diff --git a/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/DefaultSchemaService.java b/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/DefaultSchemaService.java index 060dabd37827..6df7eb1b3517 100644 --- a/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/DefaultSchemaService.java +++ b/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/DefaultSchemaService.java @@ -40,10 +40,10 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import javax.persistence.EntityManagerFactory; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.hibernate.MappingException; -import org.hibernate.SessionFactory; import org.hibernate.metamodel.spi.MetamodelImplementor; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.SingleTableEntityPersister; @@ -338,16 +338,17 @@ private void init() { private final PropertyIntrospectorService propertyIntrospectorService; - private final SessionFactory sessionFactory; + private final EntityManagerFactory entityManagerFactory; @Autowired public DefaultSchemaService( - PropertyIntrospectorService propertyIntrospectorService, SessionFactory sessionFactory) { + PropertyIntrospectorService propertyIntrospectorService, + EntityManagerFactory entityManagerFactory) { checkNotNull(propertyIntrospectorService); - checkNotNull(sessionFactory); + checkNotNull(entityManagerFactory); this.propertyIntrospectorService = propertyIntrospectorService; - this.sessionFactory = sessionFactory; + this.entityManagerFactory = entityManagerFactory; init(); } @@ -371,7 +372,7 @@ public void handleContextRefresh(ContextRefreshedEvent contextRefreshedEvent) { Schema schema = descriptor.getSchema(); MetamodelImplementor metamodelImplementor = - (MetamodelImplementor) sessionFactory.getMetamodel(); + (MetamodelImplementor) entityManagerFactory.getMetamodel(); try { EntityPersister entityPersister = metamodelImplementor.entityPersister(schema.getKlass()); diff --git a/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/introspection/HibernatePropertyIntrospector.java b/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/introspection/HibernatePropertyIntrospector.java index 02b02b00b070..edcc5c55ff8c 100644 --- a/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/introspection/HibernatePropertyIntrospector.java +++ b/dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/introspection/HibernatePropertyIntrospector.java @@ -34,8 +34,8 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; +import javax.persistence.EntityManagerFactory; import org.hibernate.MappingException; -import org.hibernate.SessionFactory; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.mapping.Column; @@ -67,14 +67,14 @@ * @author Jan Bernitt (extraction to this class) */ public class HibernatePropertyIntrospector implements PropertyIntrospector { - private final SessionFactory sessionFactory; + private final EntityManagerFactory entityManagerFactory; private final Map roleToRole = new ConcurrentHashMap<>(); private final AtomicBoolean roleToRoleComputing = new AtomicBoolean(false); - public HibernatePropertyIntrospector(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; + public HibernatePropertyIntrospector(EntityManagerFactory entityManager) { + this.entityManagerFactory = entityManager; } private void updateJoinTables() { @@ -87,7 +87,8 @@ private void updateJoinTables() { Map> joinTableToRoles = new HashMap<>(); SessionFactoryImplementor sessionFactoryImplementor = - (SessionFactoryImplementor) sessionFactory; + entityManagerFactory.unwrap(SessionFactoryImplementor.class); + MetamodelImplementor metamodelImplementor = sessionFactoryImplementor.getMetamodel(); for (CollectionPersister collectionPersister : @@ -150,7 +151,7 @@ public void introspect(Class klass, Map properties) { } private MetamodelImplementor getMetamodelImplementor() { - return ((SessionFactoryImplementor) sessionFactory).getMetamodel(); + return entityManagerFactory.unwrap(SessionFactoryImplementor.class).getMetamodel(); } private Property createProperty( diff --git a/dhis-2/dhis-services/dhis-service-setting/pom.xml b/dhis-2/dhis-services/dhis-service-setting/pom.xml index be8513e20b92..343b4f346bdb 100644 --- a/dhis-2/dhis-services/dhis-service-setting/pom.xml +++ b/dhis-2/dhis-services/dhis-service-setting/pom.xml @@ -33,10 +33,6 @@ org.springframework spring-tx - - org.hibernate - hibernate-core - javax.persistence javax.persistence-api diff --git a/dhis-2/dhis-services/dhis-service-setting/src/main/java/org/hisp/dhis/setting/hibernate/HibernateSystemSettingStore.java b/dhis-2/dhis-services/dhis-service-setting/src/main/java/org/hisp/dhis/setting/hibernate/HibernateSystemSettingStore.java index 18086b390c16..7845f9583da8 100644 --- a/dhis-2/dhis-services/dhis-service-setting/src/main/java/org/hisp/dhis/setting/hibernate/HibernateSystemSettingStore.java +++ b/dhis-2/dhis-services/dhis-service-setting/src/main/java/org/hisp/dhis/setting/hibernate/HibernateSystemSettingStore.java @@ -27,8 +27,8 @@ */ package org.hisp.dhis.setting.hibernate; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; -import org.hibernate.SessionFactory; import org.hisp.dhis.hibernate.HibernateGenericStore; import org.hisp.dhis.setting.SystemSetting; import org.hisp.dhis.setting.SystemSettingStore; @@ -43,10 +43,8 @@ public class HibernateSystemSettingStore extends HibernateGenericStore implements SystemSettingStore { public HibernateSystemSettingStore( - SessionFactory sessionFactory, - JdbcTemplate jdbcTemplate, - ApplicationEventPublisher publisher) { - super(sessionFactory, jdbcTemplate, publisher, SystemSetting.class, true); + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher) { + super(entityManager, jdbcTemplate, publisher, SystemSetting.class, true); } @Override diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/enrollment/HibernateEnrollmentStore.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/enrollment/HibernateEnrollmentStore.java index 2e5f44801dcb..6cfeca6e2a42 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/enrollment/HibernateEnrollmentStore.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/enrollment/HibernateEnrollmentStore.java @@ -41,13 +41,13 @@ import java.util.function.IntSupplier; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import lombok.Builder; import lombok.Getter; import org.apache.commons.lang3.StringUtils; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.common.OrganisationUnitSelectionMode; import org.hisp.dhis.common.Pager; @@ -86,13 +86,13 @@ class HibernateEnrollmentStore extends SoftDeleteHibernateObjectStore= :enrollmentOccurredAfter ) "); + fromBuilder.append(hlp.whereAnd()).append(" (en.occurreddate >= :enrollmentOccurredAfter ) "); } if (params.getScheduleAtStartDate() != null) { diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/relationship/HibernateRelationshipStore.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/relationship/HibernateRelationshipStore.java index 251297265f80..8268b2f94719 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/relationship/HibernateRelationshipStore.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/relationship/HibernateRelationshipStore.java @@ -33,13 +33,13 @@ import java.util.function.Function; import java.util.function.IntSupplier; import javax.annotation.Nonnull; +import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.Subquery; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.common.Pager; import org.hisp.dhis.common.hibernate.SoftDeleteHibernateObjectStore; @@ -78,13 +78,13 @@ class HibernateRelationshipStore extends SoftDeleteHibernateObjectStore= '") + .append("AND EN.occurreddate >= '") .append(getLongDateString(params.getProgramIncidentStartDate())) .append("' "); } if (params.hasProgramIncidentEndDate()) { program - .append("AND EN.incidentdate <= '") + .append("AND EN.occurreddate <= '") .append(getLongDateString(params.getProgramIncidentEndDate())) .append("' "); } diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/mapper/EnrollmentRowCallbackHandler.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/mapper/EnrollmentRowCallbackHandler.java index 73f462c7559f..8850757c2cdf 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/mapper/EnrollmentRowCallbackHandler.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/mapper/EnrollmentRowCallbackHandler.java @@ -98,7 +98,7 @@ private Enrollment getEnrollment(ResultSet rs) throws SQLException { enrollment.setEnrollmentDate( rs.getTimestamp(EnrollmentQuery.getColumnName(COLUMNS.ENROLLMENTDATE))); enrollment.setOccurredDate( - rs.getTimestamp(EnrollmentQuery.getColumnName(COLUMNS.INCIDENTDATE))); + rs.getTimestamp(EnrollmentQuery.getColumnName(COLUMNS.OCCURREDDATE))); enrollment.setCompletedDate(rs.getTimestamp(EnrollmentQuery.getColumnName(COLUMNS.COMPLETED))); enrollment.setCompletedBy(rs.getString(EnrollmentQuery.getColumnName(COLUMNS.COMPLETEDBY))); enrollment.setStoredBy(rs.getString(EnrollmentQuery.getColumnName(COLUMNS.STOREDBY))); diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/query/EnrollmentQuery.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/query/EnrollmentQuery.java index b264122eca7f..dcd7aa5f84c7 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/query/EnrollmentQuery.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/query/EnrollmentQuery.java @@ -47,7 +47,7 @@ public enum COLUMNS { STATUS, GEOMETRY, ENROLLMENTDATE, - INCIDENTDATE, + OCCURREDDATE, FOLLOWUP, COMPLETED, COMPLETEDBY, @@ -74,7 +74,7 @@ public enum COLUMNS { .put(COLUMNS.LAST_UPDATED_BY, new TableColumn("en", "lastupdatedbyuserinfo")) .put(COLUMNS.STATUS, new TableColumn("en", "status")) .put(COLUMNS.ENROLLMENTDATE, new TableColumn("en", "enrollmentdate")) - .put(COLUMNS.INCIDENTDATE, new TableColumn("en", "incidentdate")) + .put(COLUMNS.OCCURREDDATE, new TableColumn("en", "occurreddate")) .put(COLUMNS.FOLLOWUP, new TableColumn("en", "followup")) .put(COLUMNS.COMPLETED, new TableColumn("en", "completeddate")) .put(COLUMNS.COMPLETEDBY, new TableColumn("en", "completedby")) diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/DefaultTrackerBundleService.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/DefaultTrackerBundleService.java index a8699eadad70..2a1564f61d39 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/DefaultTrackerBundleService.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/DefaultTrackerBundleService.java @@ -32,9 +32,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import javax.persistence.EntityManager; import lombok.RequiredArgsConstructor; -import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hisp.dhis.trackedentity.TrackedEntityService; import org.hisp.dhis.tracker.TrackerType; import org.hisp.dhis.tracker.imports.ParamsConverter; @@ -62,7 +61,7 @@ public class DefaultTrackerBundleService implements TrackerBundleService { private final TrackerPreheatService trackerPreheatService; - private final SessionFactory sessionFactory; + private final EntityManager entityManager; private final CommitService commitService; @@ -104,17 +103,16 @@ public PersistenceReport commit(TrackerBundle bundle) { return PersistenceReport.emptyReport(); } - Session session = sessionFactory.getCurrentSession(); Map reportMap = Map.of( TrackerType.TRACKED_ENTITY, - commitService.getTrackerPersister().persist(session, bundle), + commitService.getTrackerPersister().persist(entityManager, bundle), TrackerType.ENROLLMENT, - commitService.getEnrollmentPersister().persist(session, bundle), + commitService.getEnrollmentPersister().persist(entityManager, bundle), TrackerType.EVENT, - commitService.getEventPersister().persist(session, bundle), + commitService.getEventPersister().persist(entityManager, bundle), TrackerType.RELATIONSHIP, - commitService.getRelationshipPersister().persist(session, bundle)); + commitService.getRelationshipPersister().persist(entityManager, bundle)); return new PersistenceReport(reportMap); } diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/AbstractTrackerPersister.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/AbstractTrackerPersister.java index 92ca5a9a6634..5285fb71f4c6 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/AbstractTrackerPersister.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/AbstractTrackerPersister.java @@ -37,11 +37,11 @@ import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; +import javax.persistence.EntityManager; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.hibernate.Session; import org.hisp.dhis.common.AuditType; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.ValueType; @@ -81,12 +81,12 @@ public abstract class AbstractTrackerPersister< * Template method that can be used by classes extending this class to execute the persistence * flow of Tracker entities * - * @param session a valid Hibernate Session + * @param entityManager a valid EntityManager * @param bundle the Bundle to persist * @return a {@link TrackerTypeReport} */ @Override - public TrackerTypeReport persist(Session session, TrackerBundle bundle) { + public TrackerTypeReport persist(EntityManager entityManager, TrackerBundle bundle) { // // Init the report that will hold the results of the persist operation // @@ -114,27 +114,27 @@ public TrackerTypeReport persist(Session session, TrackerBundle bundle) { // // Handle notes persistence, if required // - persistNotes(session, bundle.getPreheat(), convertedDto); + persistNotes(entityManager, bundle.getPreheat(), convertedDto); // // Handle ownership records, if required // persistOwnership(bundle.getPreheat(), convertedDto); - updateDataValues(session, bundle.getPreheat(), trackerDto, convertedDto); + updateDataValues(entityManager, bundle.getPreheat(), trackerDto, convertedDto); // // Save or update the entity // if (isNew(bundle.getPreheat(), trackerDto)) { - session.persist(convertedDto); + entityManager.persist(convertedDto); typeReport.getStats().incCreated(); typeReport.addEntity(objectReport); - updateAttributes(session, bundle.getPreheat(), trackerDto, convertedDto); + updateAttributes(entityManager, bundle.getPreheat(), trackerDto, convertedDto); } else { if (isUpdatable()) { - updateAttributes(session, bundle.getPreheat(), trackerDto, convertedDto); - session.merge(convertedDto); + updateAttributes(entityManager, bundle.getPreheat(), trackerDto, convertedDto); + entityManager.merge(convertedDto); typeReport.getStats().incUpdated(); typeReport.addEntity(objectReport); Optional.ofNullable(getUpdatedTrackedEntity(convertedDto)) @@ -150,7 +150,7 @@ public TrackerTypeReport persist(Session session, TrackerBundle bundle) { updatePreheat(bundle.getPreheat(), convertedDto); if (FlushMode.OBJECT == bundle.getFlushMode()) { - session.flush(); + entityManager.flush(); } if (!bundle.isSkipSideEffects()) { @@ -200,18 +200,19 @@ public TrackerTypeReport persist(Session session, TrackerBundle bundle) { protected abstract V convert(TrackerBundle bundle, T trackerDto); /** Persists the notes for the given entity, if the entity has notes */ - protected abstract void persistNotes(Session session, TrackerPreheat preheat, V entity); + protected abstract void persistNotes( + EntityManager entityManager, TrackerPreheat preheat, V entity); /** Persists ownership records for the given entity */ protected abstract void persistOwnership(TrackerPreheat preheat, V entity); /** Execute the persistence of Data values linked to the entity being processed */ protected abstract void updateDataValues( - Session session, TrackerPreheat preheat, T trackerDto, V hibernateEntity); + EntityManager entityManager, TrackerPreheat preheat, T trackerDto, V hibernateEntity); /** Execute the persistence of Attribute values linked to the entity being processed */ protected abstract void updateAttributes( - Session session, TrackerPreheat preheat, T trackerDto, V hibernateEntity); + EntityManager entityManager, TrackerPreheat preheat, T trackerDto, V hibernateEntity); /** Updates the {@link TrackerPreheat} object with the entity that has been persisted */ protected abstract void updatePreheat(TrackerPreheat preheat, V convertedDto); @@ -261,17 +262,17 @@ private List getByType(TrackerType type, TrackerBundle bundle) { // // // // // // // // protected void assignFileResource( - Session session, TrackerPreheat preheat, String fileResourceOwner, String fr) { - assignFileResource(session, preheat, fileResourceOwner, fr, true); + EntityManager entityManager, TrackerPreheat preheat, String fileResourceOwner, String fr) { + assignFileResource(entityManager, preheat, fileResourceOwner, fr, true); } protected void unassignFileResource( - Session session, TrackerPreheat preheat, String fileResourceOwner, String fr) { - assignFileResource(session, preheat, fileResourceOwner, fr, false); + EntityManager entityManager, TrackerPreheat preheat, String fileResourceOwner, String fr) { + assignFileResource(entityManager, preheat, fileResourceOwner, fr, false); } private void assignFileResource( - Session session, + EntityManager entityManager, TrackerPreheat preheat, String fileResourceOwner, String fr, @@ -284,11 +285,11 @@ private void assignFileResource( fileResource.setAssigned(isAssign); fileResource.setFileResourceOwner(fileResourceOwner); - session.merge(fileResource); + entityManager.merge(fileResource); } protected void handleTrackedEntityAttributeValues( - Session session, + EntityManager entityManager, TrackerPreheat preheat, List payloadAttributes, TrackedEntity trackedEntity) { @@ -323,7 +324,7 @@ protected void handleTrackedEntityAttributeValues( } if (isDelete) { - delete(session, preheat, trackedEntityAttributeValue, trackedEntity); + delete(entityManager, preheat, trackedEntityAttributeValue, trackedEntity); } else { if (!isNew) { isUpdated = !trackedEntityAttributeValue.getPlainValue().equals(attribute.getValue()); @@ -342,7 +343,12 @@ protected void handleTrackedEntityAttributeValues( .setValue(attribute.getValue()); saveOrUpdate( - session, preheat, isNew, trackedEntity, trackedEntityAttributeValue, isUpdated); + entityManager, + preheat, + isNew, + trackedEntity, + trackedEntityAttributeValue, + isUpdated); } handleReservedValue(trackedEntityAttributeValue); @@ -350,23 +356,26 @@ protected void handleTrackedEntityAttributeValues( } private void delete( - Session session, + EntityManager entityManager, TrackerPreheat preheat, TrackedEntityAttributeValue trackedEntityAttributeValue, TrackedEntity trackedEntity) { if (isFileResource(trackedEntityAttributeValue)) { unassignFileResource( - session, preheat, trackedEntity.getUid(), trackedEntityAttributeValue.getValue()); + entityManager, preheat, trackedEntity.getUid(), trackedEntityAttributeValue.getValue()); } - session.remove(trackedEntityAttributeValue); + entityManager.remove( + entityManager.contains(trackedEntityAttributeValue) + ? trackedEntityAttributeValue + : entityManager.merge(trackedEntityAttributeValue)); logTrackedEntityAttributeValueHistory( preheat.getUsername(), trackedEntityAttributeValue, trackedEntity, AuditType.DELETE); } private void saveOrUpdate( - Session session, + EntityManager entityManager, TrackerPreheat preheat, boolean isNew, TrackedEntity trackedEntity, @@ -374,19 +383,19 @@ private void saveOrUpdate( boolean isUpdated) { if (isFileResource(trackedEntityAttributeValue)) { assignFileResource( - session, preheat, trackedEntity.getUid(), trackedEntityAttributeValue.getValue()); + entityManager, preheat, trackedEntity.getUid(), trackedEntityAttributeValue.getValue()); } AuditType auditType = null; if (isNew) { - session.persist(trackedEntityAttributeValue); + entityManager.persist(trackedEntityAttributeValue); // In case it's a newly created attribute we'll add it back to TE, // so it can end up in preheat trackedEntity.getTrackedEntityAttributeValues().add(trackedEntityAttributeValue); auditType = AuditType.CREATE; } else { - session.merge(trackedEntityAttributeValue); + entityManager.merge(trackedEntityAttributeValue); if (isUpdated) { auditType = AuditType.UPDATE; diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/EnrollmentPersister.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/EnrollmentPersister.java index 3d3af68b6a42..1f907ab6a0be 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/EnrollmentPersister.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/EnrollmentPersister.java @@ -30,7 +30,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Objects; -import org.hibernate.Session; +import javax.persistence.EntityManager; import org.hisp.dhis.note.Note; import org.hisp.dhis.program.Enrollment; import org.hisp.dhis.reservedvalue.ReservedValueService; @@ -73,12 +73,12 @@ public EnrollmentPersister( @Override protected void updateAttributes( - Session session, + EntityManager entityManager, TrackerPreheat preheat, org.hisp.dhis.tracker.imports.domain.Enrollment enrollment, Enrollment enrollmentToPersist) { handleTrackedEntityAttributeValues( - session, + entityManager, preheat, enrollment.getAttributes(), preheat.getTrackedEntity(enrollmentToPersist.getTrackedEntity().getUid())); @@ -86,7 +86,7 @@ protected void updateAttributes( @Override protected void updateDataValues( - Session session, + EntityManager entityManager, TrackerPreheat preheat, org.hisp.dhis.tracker.imports.domain.Enrollment enrollment, Enrollment enrollmentToPersist) { @@ -94,11 +94,12 @@ protected void updateDataValues( } @Override - protected void persistNotes(Session session, TrackerPreheat preheat, Enrollment enrollment) { + protected void persistNotes( + EntityManager entityManager, TrackerPreheat preheat, Enrollment enrollment) { if (!enrollment.getNotes().isEmpty()) { for (Note note : enrollment.getNotes()) { if (Objects.isNull(preheat.getNote(note.getUid()))) { - session.persist(note); + entityManager.persist(note); } } } diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/EventPersister.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/EventPersister.java index 523251f4d334..9a827e94e0fe 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/EventPersister.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/EventPersister.java @@ -39,10 +39,10 @@ import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; +import javax.persistence.EntityManager; import lombok.Builder; import lombok.Data; import org.apache.commons.lang3.StringUtils; -import org.hibernate.Session; import org.hisp.dhis.common.AuditType; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.eventdatavalue.EventDataValue; @@ -88,11 +88,11 @@ public EventPersister( } @Override - protected void persistNotes(Session session, TrackerPreheat preheat, Event event) { + protected void persistNotes(EntityManager entityManager, TrackerPreheat preheat, Event event) { if (!event.getNotes().isEmpty()) { for (Note note : event.getNotes()) { if (Objects.isNull(preheat.getNote(note.getUid()))) { - session.save(note); + entityManager.persist(note); } } } @@ -135,7 +135,7 @@ protected TrackerType getType() { @Override protected void updateAttributes( - Session session, + EntityManager entityManager, TrackerPreheat preheat, org.hisp.dhis.tracker.imports.domain.Event event, Event hibernateEntity) { @@ -144,15 +144,18 @@ protected void updateAttributes( @Override protected void updateDataValues( - Session session, + EntityManager entityManager, TrackerPreheat preheat, org.hisp.dhis.tracker.imports.domain.Event event, Event hibernateEntity) { - handleDataValues(session, preheat, event.getDataValues(), hibernateEntity); + handleDataValues(entityManager, preheat, event.getDataValues(), hibernateEntity); } private void handleDataValues( - Session session, TrackerPreheat preheat, Set payloadDataValues, Event event) { + EntityManager entityManager, + TrackerPreheat preheat, + Set payloadDataValues, + Event event) { Map dataValueDBMap = Optional.ofNullable(preheat.getEvent(event.getUid())) .map( @@ -181,7 +184,8 @@ private void handleDataValues( if (StringUtils.isEmpty(dv.getValue())) { if (dataElement.isFileType()) { - unassignFileResource(session, preheat, event.getUid(), eventDataValue.getValue()); + unassignFileResource( + entityManager, preheat, event.getUid(), eventDataValue.getValue()); } event.getEventDataValues().remove(eventDataValue); @@ -189,7 +193,7 @@ private void handleDataValues( eventDataValue.setValue(dv.getValue()); if (dataElement.isFileType()) { - assignFileResource(session, preheat, event.getUid(), eventDataValue.getValue()); + assignFileResource(entityManager, preheat, event.getUid(), eventDataValue.getValue()); } event.getEventDataValues().remove(eventDataValue); diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/RelationshipPersister.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/RelationshipPersister.java index 855497767326..0a663fbbbfd4 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/RelationshipPersister.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/RelationshipPersister.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.tracker.imports.bundle.persister; -import org.hibernate.Session; +import javax.persistence.EntityManager; import org.hisp.dhis.reservedvalue.ReservedValueService; import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValueAuditService; import org.hisp.dhis.tracker.TrackerType; @@ -65,13 +65,15 @@ protected org.hisp.dhis.relationship.Relationship convert( @Override protected void persistNotes( - Session session, TrackerPreheat preheat, org.hisp.dhis.relationship.Relationship entity) { + EntityManager entityManager, + TrackerPreheat preheat, + org.hisp.dhis.relationship.Relationship entity) { // NOTHING TO DO } @Override protected void updateAttributes( - Session session, + EntityManager entityManager, TrackerPreheat preheat, Relationship trackerDto, org.hisp.dhis.relationship.Relationship hibernateEntity) { @@ -80,7 +82,7 @@ protected void updateAttributes( @Override protected void updateDataValues( - Session session, + EntityManager entityManager, TrackerPreheat preheat, Relationship trackerDto, org.hisp.dhis.relationship.Relationship hibernateEntity) { diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/TrackedEntityPersister.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/TrackedEntityPersister.java index b205475f627a..4d9da077085d 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/TrackedEntityPersister.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/TrackedEntityPersister.java @@ -29,7 +29,7 @@ import java.util.Collections; import javax.annotation.Nonnull; -import org.hibernate.Session; +import javax.persistence.EntityManager; import org.hisp.dhis.reservedvalue.ReservedValueService; import org.hisp.dhis.trackedentity.TrackedEntity; import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValueAuditService; @@ -63,16 +63,16 @@ public TrackedEntityPersister( @Override protected void updateAttributes( - Session session, + EntityManager entityManager, TrackerPreheat preheat, org.hisp.dhis.tracker.imports.domain.TrackedEntity trackerDto, TrackedEntity te) { - handleTrackedEntityAttributeValues(session, preheat, trackerDto.getAttributes(), te); + handleTrackedEntityAttributeValues(entityManager, preheat, trackerDto.getAttributes(), te); } @Override protected void updateDataValues( - Session session, + EntityManager entityManager, TrackerPreheat preheat, org.hisp.dhis.tracker.imports.domain.TrackedEntity trackerDto, TrackedEntity te) { @@ -81,7 +81,7 @@ protected void updateDataValues( @Override protected void persistNotes( - Session session, TrackerPreheat preheat, TrackedEntity trackedEntity) { + EntityManager entityManager, TrackerPreheat preheat, TrackedEntity trackedEntity) { // DO NOTHING - TE HAVE NO NOTES } diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/TrackerPersister.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/TrackerPersister.java index e48af7f37cf5..102832a3ddcf 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/TrackerPersister.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/imports/bundle/persister/TrackerPersister.java @@ -27,7 +27,7 @@ */ package org.hisp.dhis.tracker.imports.bundle.persister; -import org.hibernate.Session; +import javax.persistence.EntityManager; import org.hisp.dhis.tracker.imports.bundle.TrackerBundle; import org.hisp.dhis.tracker.imports.domain.TrackerDto; import org.hisp.dhis.tracker.imports.report.TrackerTypeReport; @@ -43,9 +43,9 @@ public interface TrackerPersister { * Persist one of the collections in the provided Tracker Bundle. Each class implementing this * method should be responsible to persist one collection of the TrackerBundle (e.g. Enrollments) * - * @param session a valid Hibernate Session + * @param entityManager a valid EntityManager * @param bundle the Bundle to persist * @return a {@link TrackerTypeReport} */ - TrackerTypeReport persist(Session session, TrackerBundle bundle); + TrackerTypeReport persist(EntityManager entityManager, TrackerBundle bundle); } diff --git a/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/dataanalysis/FollowupValueManager.java b/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/dataanalysis/FollowupValueManager.java index adbda1b1e718..a713e4474e5e 100644 --- a/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/dataanalysis/FollowupValueManager.java +++ b/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/dataanalysis/FollowupValueManager.java @@ -32,9 +32,10 @@ import static org.hisp.dhis.query.JpaQueryUtils.generateHqlQueryForSharingCheck; import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; import lombok.RequiredArgsConstructor; -import org.hibernate.SessionFactory; -import org.hibernate.query.Query; +import org.hibernate.jpa.QueryHints; import org.hisp.dhis.datavalue.DataValue; import org.hisp.dhis.period.PeriodType; import org.hisp.dhis.security.acl.AclService; @@ -50,7 +51,7 @@ @Component @RequiredArgsConstructor public class FollowupValueManager { - private final SessionFactory sessionFactory; + private final EntityManager entityManager; /** HQL query used to select {@link FollowupValue}s. */ private static final String FOLLOWUP_VALUE_HQL = @@ -111,19 +112,17 @@ public List getFollowupDataValues( User currentUser, FollowupAnalysisRequest request) { if (isEmpty(request.getDe()) && !isEmpty(request.getDs())) { request.setDe( - sessionFactory - .getCurrentSession() + entityManager .createQuery(DATA_ELEMENT_UIDS_BY_DATA_SET_UIDS_HQL, String.class) .setParameter("ds_ids", request.getDs()) - .list()); + .getResultList()); } if (!isEmpty(request.getDe()) && isEmpty(request.getCoc())) { request.setCoc( - sessionFactory - .getCurrentSession() + entityManager .createQuery(CATEGORY_OPTION_COMBO_UIDS_BY_DATE_ELEMENT_UIDS_HQL, String.class) .setParameter("de_ids", request.getDe()) - .list()); + .getResultList()); } if (isEmpty(request.getDe()) || isEmpty(request.getCoc()) || isEmpty(request.getOu())) { return emptyList(); @@ -135,15 +134,12 @@ public List getFollowupDataValues( request.setEndDate(PeriodType.getPeriodFromIsoString(request.getPe()).getEndDate()); } - Query query = - sessionFactory - .getCurrentSession() - .createQuery( - FOLLOWUP_VALUE_HQL.replace( - "<>", - generateHqlQueryForSharingCheck( - "de", currentUser, AclService.LIKE_READ_METADATA)), - FollowupValue.class); + TypedQuery query = + entityManager.createQuery( + FOLLOWUP_VALUE_HQL.replace( + "<>", + generateHqlQueryForSharingCheck("de", currentUser, AclService.LIKE_READ_METADATA)), + FollowupValue.class); query.setParameter("ou_ids", request.getOu()); query.setParameter("de_ids", request.getDe()); @@ -151,6 +147,6 @@ public List getFollowupDataValues( query.setParameter("startDate", request.getStartDate()); query.setParameter("endDate", request.getEndDate()); query.setMaxResults(request.getMaxResults()); - return query.setCacheable(false).list(); + return query.setHint(QueryHints.HINT_CACHEABLE, false).getResultList(); } } diff --git a/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/minmax/hibernate/HibernateMinMaxDataElementStore.java b/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/minmax/hibernate/HibernateMinMaxDataElementStore.java index 64322a7ea8a7..853b0621ad6a 100644 --- a/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/minmax/hibernate/HibernateMinMaxDataElementStore.java +++ b/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/minmax/hibernate/HibernateMinMaxDataElementStore.java @@ -32,11 +32,11 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.CategoryOptionCombo; import org.hisp.dhis.common.Pager; import org.hisp.dhis.dataelement.DataElement; @@ -70,13 +70,13 @@ public class HibernateMinMaxDataElementStore extends HibernateGenericStore programNotificationInstanceStore() { return new HibernateIdentifiableObjectStore( - sessionFactory, + entityManager, jdbcTemplate, publisher, ValidationNotificationTemplate.class, @@ -70,7 +71,7 @@ public class StoreConfig { @Bean("org.hisp.dhis.validation.ValidationRuleGroupStore") public HibernateIdentifiableObjectStore validationRuleGroupStore() { return new HibernateIdentifiableObjectStore( - sessionFactory, + entityManager, jdbcTemplate, publisher, ValidationRuleGroup.class, diff --git a/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/validation/hibernate/HibernateValidationResultStore.java b/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/validation/hibernate/HibernateValidationResultStore.java index 85ba7dcda9b7..c784bae40ba7 100644 --- a/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/validation/hibernate/HibernateValidationResultStore.java +++ b/dhis-2/dhis-services/dhis-service-validation/src/main/java/org/hisp/dhis/validation/hibernate/HibernateValidationResultStore.java @@ -37,9 +37,9 @@ import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nonnull; +import javax.persistence.EntityManager; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.hisp.dhis.category.Category; import org.hisp.dhis.category.CategoryOptionGroupSet; @@ -72,11 +72,11 @@ public class HibernateValidationResultStore extends HibernateGenericStore { diff --git a/dhis-2/dhis-support/dhis-support-artemis/src/main/java/org/hisp/dhis/artemis/audit/listener/HibernateListenerConfigurer.java b/dhis-2/dhis-support/dhis-support-artemis/src/main/java/org/hisp/dhis/artemis/audit/listener/HibernateListenerConfigurer.java index 6a2a81b2afe4..41a0d8a42504 100644 --- a/dhis-2/dhis-support/dhis-support-artemis/src/main/java/org/hisp/dhis/artemis/audit/listener/HibernateListenerConfigurer.java +++ b/dhis-2/dhis-support/dhis-support-artemis/src/main/java/org/hisp/dhis/artemis/audit/listener/HibernateListenerConfigurer.java @@ -30,7 +30,6 @@ import javax.annotation.Nonnull; import javax.annotation.PostConstruct; import javax.persistence.EntityManagerFactory; -import javax.persistence.PersistenceUnit; import lombok.RequiredArgsConstructor; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; @@ -65,7 +64,7 @@ public void setApplicationContext(ApplicationContext applicationContext) throws this.applicationContext = applicationContext; } - @PersistenceUnit private EntityManagerFactory emf; + @Nonnull private final EntityManagerFactory emf; @Nonnull private final PostInsertAuditListener postInsertAuditListener; diff --git a/dhis-2/dhis-support/dhis-support-commons/pom.xml b/dhis-2/dhis-support/dhis-support-commons/pom.xml index f10142563aa8..463d1594ec24 100644 --- a/dhis-2/dhis-support/dhis-support-commons/pom.xml +++ b/dhis-2/dhis-support/dhis-support-commons/pom.xml @@ -24,6 +24,10 @@ org.hisp.dhis dhis-api + + org.hisp.dhis + json-tree + org.apache.commons commons-lang3 @@ -81,10 +85,6 @@ org.apache.logging.log4j log4j-slf4j-impl - - org.hibernate - hibernate-core - com.fasterxml.jackson.core jackson-core diff --git a/dhis-2/dhis-support/dhis-support-commons/src/main/java/org/hisp/dhis/commons/jackson/config/JacksonObjectMapperConfig.java b/dhis-2/dhis-support/dhis-support-commons/src/main/java/org/hisp/dhis/commons/jackson/config/JacksonObjectMapperConfig.java index 9cb1ed4fe58d..8185562ae814 100644 --- a/dhis-2/dhis-support/dhis-support-commons/src/main/java/org/hisp/dhis/commons/jackson/config/JacksonObjectMapperConfig.java +++ b/dhis-2/dhis-support/dhis-support-commons/src/main/java/org/hisp/dhis/commons/jackson/config/JacksonObjectMapperConfig.java @@ -44,11 +44,11 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.time.Instant; import java.util.Date; -import org.hibernate.SessionFactory; import org.hisp.dhis.commons.jackson.config.geometry.GeometrySerializer; import org.hisp.dhis.commons.jackson.config.geometry.JtsXmlModule; import org.hisp.dhis.dataexchange.aggregate.Api; import org.hisp.dhis.dataexchange.aggregate.ApiSerializer; +import org.hisp.dhis.jsontree.JsonValue; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.PrecisionModel; @@ -94,8 +94,8 @@ public ObjectMapper jsonMapper() { } @Bean("hibernateAwareJsonMapper") - public ObjectMapper hibernateAwareJsonMapper(SessionFactory sessionFactory) { - Hibernate5Module hibernate5Module = new Hibernate5Module(sessionFactory); + public ObjectMapper hibernateAwareJsonMapper() { + Hibernate5Module hibernate5Module = new Hibernate5Module(); hibernate5Module.enable( Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS); hibernateAwareJsonMapper.registerModule(hibernate5Module); @@ -153,6 +153,7 @@ private static ObjectMapper configureMapper( module.addSerializer(Date.class, new WriteDateStdSerializer()); module.addSerializer(JsonPointer.class, new JsonPointerStdSerializer()); module.addSerializer(Api.class, new ApiSerializer()); + module.addSerializer(JsonValue.class, new JsonValueSerializer()); // Registering a custom Instant serializer/deserializer for DTOs JavaTimeModule javaTimeModule = new JavaTimeModule(); diff --git a/dhis-2/dhis-support/dhis-support-commons/src/main/java/org/hisp/dhis/commons/jackson/config/JsonValueSerializer.java b/dhis-2/dhis-support/dhis-support-commons/src/main/java/org/hisp/dhis/commons/jackson/config/JsonValueSerializer.java new file mode 100644 index 000000000000..cbd08c9b9ccc --- /dev/null +++ b/dhis-2/dhis-support/dhis-support-commons/src/main/java/org/hisp/dhis/commons/jackson/config/JsonValueSerializer.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2004-2023, University of Oslo + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of the HISP project nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.hisp.dhis.commons.jackson.config; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; +import org.hisp.dhis.jsontree.JsonValue; + +/** + * @author Jan Bernitt + */ +public class JsonValueSerializer extends JsonSerializer { + + @Override + public void serialize(JsonValue obj, JsonGenerator generator, SerializerProvider provider) + throws IOException { + if (obj == null) { + generator.writeNull(); + } else { + generator.writeRawValue(obj.node().getDeclaration()); + } + } +} diff --git a/dhis-2/dhis-support/dhis-support-db-migration/src/main/resources/org/hisp/dhis/db/migration/2.41/V2_41_38__RenameIncidentDateToOccurredDateInEnrollmentTable.sql b/dhis-2/dhis-support/dhis-support-db-migration/src/main/resources/org/hisp/dhis/db/migration/2.41/V2_41_38__RenameIncidentDateToOccurredDateInEnrollmentTable.sql new file mode 100644 index 000000000000..f5bf35a9455e --- /dev/null +++ b/dhis-2/dhis-support/dhis-support-db-migration/src/main/resources/org/hisp/dhis/db/migration/2.41/V2_41_38__RenameIncidentDateToOccurredDateInEnrollmentTable.sql @@ -0,0 +1,11 @@ +-- rename enddate in enrollment + +do $$ +begin + if exists(select 1 + from information_schema.columns + where table_schema != 'information_schema' and table_name='enrollment' and column_name='incidentdate') + then +alter table enrollment rename column incidentdate to occurreddate; +end if; +end $$; \ No newline at end of file diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/cache/DefaultHibernateCacheManager.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/cache/DefaultHibernateCacheManager.java index 46f6667f25ff..e898897bf86d 100644 --- a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/cache/DefaultHibernateCacheManager.java +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/cache/DefaultHibernateCacheManager.java @@ -27,6 +27,7 @@ */ package org.hisp.dhis.cache; +import javax.persistence.EntityManagerFactory; import lombok.extern.slf4j.Slf4j; import org.hibernate.SessionFactory; import org.hibernate.stat.Statistics; @@ -42,10 +43,10 @@ public class DefaultHibernateCacheManager implements HibernateCacheManager { // Dependencies // ------------------------------------------------------------------------- - private SessionFactory sessionFactory; + private EntityManagerFactory entityManagerFactory; - public void setSessionFactory(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; + public void setSessionFactory(EntityManagerFactory entityManagerFactory) { + this.entityManagerFactory = entityManagerFactory; } // ------------------------------------------------------------------------- @@ -54,14 +55,14 @@ public void setSessionFactory(SessionFactory sessionFactory) { @Override public void clearObjectCache() { - sessionFactory.getCache().evictEntityData(); - sessionFactory.getCache().evictCollectionData(); + getSessionFactory().getCache().evictEntityData(); + getSessionFactory().getCache().evictCollectionData(); } @Override public void clearQueryCache() { - sessionFactory.getCache().evictDefaultQueryRegion(); - sessionFactory.getCache().evictQueryRegions(); + getSessionFactory().getCache().evictDefaultQueryRegion(); + getSessionFactory().getCache().evictQueryRegions(); } @Override @@ -80,6 +81,10 @@ public void handleApplicationCachesCleared(ApplicationCacheClearedEvent event) { @Override public Statistics getStatistics() { - return sessionFactory.getStatistics(); + return getSessionFactory().getStatistics(); + } + + private SessionFactory getSessionFactory() { + return entityManagerFactory.unwrap(SessionFactory.class); } } diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/DataSourceConfig.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/DataSourceConfig.java index 0e63ba933fa7..4a098aae28ee 100644 --- a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/DataSourceConfig.java +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/DataSourceConfig.java @@ -48,7 +48,6 @@ import org.hisp.dhis.datasource.ReadOnlyDataSourceManager; import org.hisp.dhis.external.conf.ConfigurationKey; import org.hisp.dhis.external.conf.DhisConfigurationProvider; -import org.hisp.dhis.hibernate.HibernateConfigurationProvider; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -96,9 +95,7 @@ public JdbcTemplate readOnlyJdbcTemplate(@Qualifier("dataSource") DataSource dat return jdbcTemplate; } - static DataSource createActualDataSource( - DhisConfigurationProvider dhisConfig, - HibernateConfigurationProvider hibernateConfigurationProvider) { + static DataSource createActualDataSource(DhisConfigurationProvider dhisConfig) { String jdbcUrl = dhisConfig.getProperty(ConfigurationKey.CONNECTION_URL); String username = dhisConfig.getProperty(ConfigurationKey.CONNECTION_USERNAME); String dbPoolType = dhisConfig.getProperty(ConfigurationKey.DB_POOL_TYPE); @@ -106,7 +103,6 @@ static DataSource createActualDataSource( DatabasePoolUtils.PoolConfig poolConfig = DatabasePoolUtils.PoolConfig.builder() .dhisConfig(dhisConfig) - .hibernateConfig(hibernateConfigurationProvider) .dbPoolType(dbPoolType) .build(); @@ -182,9 +178,8 @@ public DataSource dataSource(@Qualifier("actualDataSource") DataSource actualDat } @Bean("actualDataSource") - public DataSource actualDataSource( - HibernateConfigurationProvider hibernateConfigurationProvider) { - return createActualDataSource(dhisConfig, hibernateConfigurationProvider); + public DataSource actualDataSource() { + return createActualDataSource(dhisConfig); } private static void executeAfterMethod(MethodExecutionContext executionContext) { diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/HibernateConfig.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/HibernateConfig.java index f37c9cca1242..e24f01d89788 100644 --- a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/HibernateConfig.java +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/HibernateConfig.java @@ -27,26 +27,38 @@ */ package org.hisp.dhis.config; +import java.io.IOException; +import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.Properties; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.SharedCacheMode; +import javax.persistence.ValidationMode; import javax.sql.DataSource; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.ArrayUtils; import org.hibernate.SessionFactory; import org.hisp.dhis.cache.DefaultHibernateCacheManager; import org.hisp.dhis.dbms.DbmsManager; import org.hisp.dhis.dbms.HibernateDbmsManager; -import org.hisp.dhis.deletedobject.DeletedObject; +import org.hisp.dhis.external.conf.ConfigurationKey; import org.hisp.dhis.external.conf.DhisConfigurationProvider; import org.hisp.dhis.hibernate.DefaultHibernateConfigurationProvider; +import org.hisp.dhis.hibernate.EntityManagerBeanDefinitionRegistrarPostProcessor; import org.hisp.dhis.hibernate.HibernateConfigurationProvider; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.orm.hibernate5.HibernateTransactionManager; -import org.springframework.orm.hibernate5.LocalSessionFactoryBean; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.support.TransactionTemplate; @@ -56,6 +68,7 @@ */ @Configuration @EnableTransactionManagement +@Slf4j public class HibernateConfig { @Bean("hibernateConfigurationProvider") public HibernateConfigurationProvider hibernateConfigurationProvider( @@ -67,62 +80,114 @@ public HibernateConfigurationProvider hibernateConfigurationProvider( } @Bean - @DependsOn("flyway") - public LocalSessionFactoryBean sessionFactory( - DataSource dataSource, - @Qualifier("hibernateConfigurationProvider") - HibernateConfigurationProvider hibernateConfigurationProvider) { - Objects.requireNonNull(dataSource); - Objects.requireNonNull(hibernateConfigurationProvider); - - Properties hibernateProperties = - hibernateConfigurationProvider.getConfiguration().getProperties(); - Objects.requireNonNull(hibernateProperties); - - List jarResources = hibernateConfigurationProvider.getJarResources(); - List directoryResources = hibernateConfigurationProvider.getDirectoryResources(); - - LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(dataSource); - sessionFactory.setMappingJarLocations(jarResources.toArray(new Resource[0])); - sessionFactory.setMappingDirectoryLocations(directoryResources.toArray(new Resource[0])); - sessionFactory.setAnnotatedClasses(DeletedObject.class); - sessionFactory.setHibernateProperties(hibernateProperties); - - return sessionFactory; + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); } - @Bean - public HibernateTransactionManager hibernateTransactionManager( - DataSource dataSource, SessionFactory sessionFactory) { - HibernateTransactionManager transactionManager = new HibernateTransactionManager(); - transactionManager.setSessionFactory(sessionFactory); - transactionManager.setDataSource(dataSource); - - return transactionManager; + @Bean("jpaTransactionManager") + @DependsOn("entityManagerFactory") + public JpaTransactionManager jpaTransactionManager( + @Qualifier("entityManagerFactory") EntityManagerFactory emf) { + return new JpaTransactionManager(emf); } - @Bean - public TransactionTemplate transactionTemplate(HibernateTransactionManager transactionManager) { + @Bean("transactionTemplate") + @DependsOn("jpaTransactionManager") + public TransactionTemplate transactionTemplate( + @Qualifier("jpaTransactionManager") JpaTransactionManager transactionManager) { return new TransactionTemplate(transactionManager); } @Bean - public DefaultHibernateCacheManager cacheManager(SessionFactory sessionFactory) { + public DefaultHibernateCacheManager cacheManager( + @Qualifier("entityManagerFactory") EntityManagerFactory emf) { DefaultHibernateCacheManager cacheManager = new DefaultHibernateCacheManager(); - cacheManager.setSessionFactory(sessionFactory); + cacheManager.setSessionFactory(emf.unwrap(SessionFactory.class)); + return cacheManager; } @Bean public DbmsManager dbmsManager( JdbcTemplate jdbcTemplate, - SessionFactory sessionFactory, - DefaultHibernateCacheManager cacheManager) { + DefaultHibernateCacheManager cacheManager, + EntityManager entityManager) { HibernateDbmsManager hibernateDbmsManager = new HibernateDbmsManager(); hibernateDbmsManager.setCacheManager(cacheManager); - hibernateDbmsManager.setSessionFactory(sessionFactory); + hibernateDbmsManager.setEntityManager(entityManager); hibernateDbmsManager.setJdbcTemplate(jdbcTemplate); return hibernateDbmsManager; } + + @Bean + public BeanFactoryPostProcessor entityManagerBeanDefinitionRegistrarPostProcessor() { + return new EntityManagerBeanDefinitionRegistrarPostProcessor(); + } + + @Bean("entityManagerFactory") + @DependsOn({"flyway"}) + public EntityManagerFactory entityManagerFactoryBean( + DhisConfigurationProvider dhisConfig, DataSource dataSource) { + HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); + adapter.setDatabasePlatform(dhisConfig.getProperty(ConfigurationKey.CONNECTION_DIALECT)); + adapter.setGenerateDdl(shouldGenerateDDL(dhisConfig)); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(adapter); + factory.setPersistenceUnitName("dhis"); + factory.setPersistenceProvider(new org.hibernate.jpa.HibernatePersistenceProvider()); + factory.setDataSource(dataSource); + factory.setPackagesToScan("org.hisp.dhis"); + factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE); + factory.setValidationMode(ValidationMode.AUTO); + factory.setJpaProperties(getAdditionalProperties()); + factory.setMappingResources(loadResources()); + factory.afterPropertiesSet(); + return factory.getObject(); + } + + /** + * Returns additional properties to be used by the {@link LocalContainerEntityManagerFactoryBean} + */ + private Properties getAdditionalProperties() { + Properties properties = new Properties(); + properties.put( + "hibernate.current_session_context_class", + "org.springframework.orm.hibernate5.SpringSessionContext"); + + // TODO: this is anti-pattern and should be turn off + properties.put("hibernate.allow_update_outside_transaction", "true"); + + return properties; + } + + /** + * Loads all the hibernate mapping files from the classpath + * + * @return Array of Strings representing the mapping files + */ + private String[] loadResources() { + try { + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + Resource[] resources = resolver.getResources("classpath*:org/hisp/dhis/**/*.hbm.xml"); + + List list = new ArrayList<>(); + for (Resource resource : resources) { + String url = resource.getURL().toString(); + list.add(url); + } + return list.toArray(new String[0]); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + return ArrayUtils.EMPTY_STRING_ARRAY; + } + + /** + * If return true, hibernate will generate the DDL for the database. This is used by h2-test. + * @param dhisConfig {@link DhisConfigurationProvider + * @return TRUE if connection.schema is not set to none + */ + private boolean shouldGenerateDDL(DhisConfigurationProvider dhisConfig) { + return "update".equals(dhisConfig.getProperty(ConfigurationKey.CONNECTION_SCHEMA)); + } } diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/HibernateEncryptionConfig.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/HibernateEncryptionConfig.java index f149060a34c2..8fbd909bc23e 100644 --- a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/HibernateEncryptionConfig.java +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/config/HibernateEncryptionConfig.java @@ -40,6 +40,7 @@ import org.springframework.beans.factory.config.MethodInvokingFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; /** * @author Luciano Fiandesio @@ -50,7 +51,7 @@ public class HibernateEncryptionConfig { public static final String AES_128_STRING_ENCRYPTOR = "aes128StringEncryptor"; - @Autowired private HibernateConfigurationProvider hibernateConfigurationProvider; + @Autowired @Lazy private HibernateConfigurationProvider hibernateConfigurationProvider; private String password; diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/datasource/DatabasePoolUtils.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/datasource/DatabasePoolUtils.java index 417b3bafac9b..27c9bd99ffc4 100644 --- a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/datasource/DatabasePoolUtils.java +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/datasource/DatabasePoolUtils.java @@ -89,7 +89,6 @@ import org.hisp.dhis.common.CodeGenerator; import org.hisp.dhis.external.conf.ConfigurationKey; import org.hisp.dhis.external.conf.DhisConfigurationProvider; -import org.hisp.dhis.hibernate.HibernateConfigurationProvider; /** * @author Morten Svanæs @@ -155,8 +154,6 @@ public static class PoolConfig { private DhisConfigurationProvider dhisConfig; - private HibernateConfigurationProvider hibernateConfig; - private String jdbcUrl; private String username; diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/dbms/DbmsUtils.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/dbms/DbmsUtils.java index 9e100cfb5587..b38a25efc18b 100644 --- a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/dbms/DbmsUtils.java +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/dbms/DbmsUtils.java @@ -27,12 +27,12 @@ */ package org.hisp.dhis.dbms; -import org.hibernate.Session; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; import org.hibernate.StatelessSession; import org.hisp.dhis.commons.util.DebugUtils; -import org.springframework.orm.hibernate5.SessionFactoryUtils; -import org.springframework.orm.hibernate5.SessionHolder; +import org.springframework.orm.jpa.EntityManagerFactoryUtils; +import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -40,17 +40,17 @@ * @version $Id$ */ public class DbmsUtils { - public static void bindSessionToThread(SessionFactory sessionFactory) { - Session session = sessionFactory.openSession(); - - TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); + public static void bindSessionToThread(EntityManagerFactory entityManagerFactory) { + EntityManager entityManager = entityManagerFactory.createEntityManager(); + TransactionSynchronizationManager.bindResource( + entityManagerFactory, new EntityManagerHolder(entityManager)); } - public static void unbindSessionFromThread(SessionFactory sessionFactory) { - SessionHolder sessionHolder = - (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); - - SessionFactoryUtils.closeSession(sessionHolder.getSession()); + public static void unbindSessionFromThread(EntityManagerFactory entityManagerFactory) { + EntityManagerHolder entityManagerHolder = + (EntityManagerHolder) + TransactionSynchronizationManager.unbindResource(entityManagerFactory); + EntityManagerFactoryUtils.closeEntityManager(entityManagerHolder.getEntityManager()); } public static void closeStatelessSession(StatelessSession session) { diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/dbms/HibernateDbmsManager.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/dbms/HibernateDbmsManager.java index e21535dc380d..f33d9a9f5002 100644 --- a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/dbms/HibernateDbmsManager.java +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/dbms/HibernateDbmsManager.java @@ -27,19 +27,20 @@ */ package org.hisp.dhis.dbms; -import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import javax.persistence.EntityManager; import lombok.extern.slf4j.Slf4j; -import org.hibernate.SessionFactory; import org.hisp.dhis.cache.HibernateCacheManager; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; +import org.springframework.stereotype.Component; /** * @author Lars Helge Overland */ +@Component @Slf4j public class HibernateDbmsManager implements DbmsManager { // ------------------------------------------------------------------------- @@ -52,10 +53,10 @@ public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } - private SessionFactory sessionFactory; + private EntityManager entityManager; - public void setSessionFactory(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; + public void setEntityManager(EntityManager entityManager) { + this.entityManager = entityManager; } private HibernateCacheManager cacheManager; @@ -358,13 +359,13 @@ public void emptyDatabase() { @Override public void clearSession() { - sessionFactory.getCurrentSession().flush(); - sessionFactory.getCurrentSession().clear(); + entityManager.flush(); + entityManager.clear(); } @Override public void flushSession() { - sessionFactory.getCurrentSession().flush(); + entityManager.flush(); } @Override @@ -438,19 +439,4 @@ private void emptyRelationships() { log.debug("Could not empty relationship tables"); } } - - @Override - public void evictObject(Object object) { - sessionFactory.getCurrentSession().evict(object); - } - - @Override - public boolean contains(Object object) { - return sessionFactory.getCurrentSession().contains(object); - } - - @Override - public Serializable getIdentifier(Object object) { - return sessionFactory.getCurrentSession().getIdentifier(object); - } } diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/hibernate/EntityManagerBeanDefinitionRegistrarPostProcessor.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/hibernate/EntityManagerBeanDefinitionRegistrarPostProcessor.java new file mode 100644 index 000000000000..fc68ea6fa76a --- /dev/null +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/hibernate/EntityManagerBeanDefinitionRegistrarPostProcessor.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2004-2023, University of Oslo + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of the HISP project nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.hisp.dhis.hibernate; + +import static java.util.Arrays.asList; +import static org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors; + +import java.util.HashSet; +import java.util.Set; +import javax.persistence.EntityManagerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.AutowireCandidateQualifier; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean; + +/** This class allows injecting {@link javax.persistence.EntityManager} using Constructor. */ +public class EntityManagerBeanDefinitionRegistrarPostProcessor implements BeanFactoryPostProcessor { + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) + throws BeansException { + if (!(beanFactory instanceof BeanDefinitionRegistry)) { + return; + } + + for (String emfName : getEntityManagerFactoryBeanNames(beanFactory)) { + if (emfName.equals("sessionFactory")) { + continue; + } + BeanDefinitionBuilder builder = + BeanDefinitionBuilder.rootBeanDefinition( + "org.springframework.orm.jpa.SharedEntityManagerCreator"); + builder.setFactoryMethod("createSharedEntityManager"); + builder.addConstructorArgReference(emfName); + + AbstractBeanDefinition emBeanDefinition = builder.getRawBeanDefinition(); + AbstractBeanDefinition emfBeanDefinition = + (AbstractBeanDefinition) beanFactory.getBeanDefinition(emfName); + + emBeanDefinition.addQualifier(new AutowireCandidateQualifier(Qualifier.class, emfName)); + emBeanDefinition.setScope(emfBeanDefinition.getScope()); + emBeanDefinition.setSource(emfBeanDefinition.getSource()); + + BeanDefinitionReaderUtils.registerWithGeneratedName( + emBeanDefinition, (BeanDefinitionRegistry) beanFactory); + } + } + + /** + * Return all bean names for bean definitions that will result in an {@link EntityManagerFactory} + * eventually. We're checking for {@link EntityManagerFactory} and the well-known factory beans + * here to avoid eager initialization of the factory beans. The double lookup is necessary + * especially for JavaConfig scenarios as people might declare an {@link EntityManagerFactory} + * directly. + * + * @param beanFactory + * @return + */ + private static Iterable getEntityManagerFactoryBeanNames( + ListableBeanFactory beanFactory) { + + Set names = + new HashSet<>( + asList( + beanNamesForTypeIncludingAncestors( + beanFactory, EntityManagerFactory.class, true, false))); + + for (String factoryBeanName : + beanNamesForTypeIncludingAncestors( + beanFactory, AbstractEntityManagerFactoryBean.class, true, false)) { + names.add(factoryBeanName.substring(1)); + } + + return names; + } +} diff --git a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/hibernate/HibernateGenericStore.java b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/hibernate/HibernateGenericStore.java index 07e655eb6e1e..3eb962e34ee2 100644 --- a/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/hibernate/HibernateGenericStore.java +++ b/dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/hibernate/HibernateGenericStore.java @@ -40,6 +40,7 @@ import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; +import javax.persistence.EntityManager; import javax.persistence.NonUniqueResultException; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; @@ -50,8 +51,6 @@ import javax.persistence.criteria.Root; import lombok.extern.slf4j.Slf4j; import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.StatelessSession; import org.hibernate.annotations.QueryHints; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.query.NativeQuery; @@ -76,7 +75,7 @@ public class HibernateGenericStore implements GenericStore { protected static final int OBJECT_FETCH_SIZE = 2000; - protected SessionFactory sessionFactory; + protected EntityManager entityManager; protected JdbcTemplate jdbcTemplate; @@ -87,17 +86,17 @@ public class HibernateGenericStore implements GenericStore { protected boolean cacheable; public HibernateGenericStore( - SessionFactory sessionFactory, + EntityManager entityManager, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, Class clazz, boolean cacheable) { - checkNotNull(sessionFactory); + checkNotNull(entityManager); checkNotNull(jdbcTemplate); checkNotNull(publisher); checkNotNull(clazz); - this.sessionFactory = sessionFactory; + this.entityManager = entityManager; this.jdbcTemplate = jdbcTemplate; this.publisher = publisher; this.clazz = clazz; @@ -131,11 +130,7 @@ public void setCacheable(boolean cacheable) { * @return the current session. */ protected final Session getSession() { - return sessionFactory.getCurrentSession(); - } - - protected final StatelessSession getStatelessSession() { - return sessionFactory.openStatelessSession(); + return entityManager.unwrap(Session.class); } /** @@ -178,7 +173,7 @@ protected final Query getTypedQuery(String hql) { protected void preProcessDetachedCriteria(DetachedCriteria detachedCriteria) {} public CriteriaBuilder getCriteriaBuilder() { - return sessionFactory.getCriteriaBuilder(); + return entityManager.getCriteriaBuilder(); } // ------------------------------------------------------------------------------------------ @@ -191,10 +186,7 @@ public CriteriaBuilder getCriteriaBuilder() { * @return executable TypedQuery */ private TypedQuery getExecutableTypedQuery(CriteriaQuery criteriaQuery) { - return getSession() - .createQuery(criteriaQuery) - .setCacheable(cacheable) - .setHint(QueryHints.CACHEABLE, cacheable); + return entityManager.createQuery(criteriaQuery).setHint(QueryHints.CACHEABLE, cacheable); } /** Method for adding additional Predicates into where clause */ @@ -382,7 +374,6 @@ protected final NativeQuery getUntypedSqlQuery(String sql) { @Override public void save(@Nonnull T object) { AuditLogUtil.infoWrapper(log, object, AuditLogUtil.ACTION_CREATE); - getSession().save(object); } diff --git a/dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/database/DatabaseInfoFactoryBean.java b/dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/database/DatabaseInfoFactoryBean.java index 5023befc4cde..20003514ed37 100644 --- a/dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/database/DatabaseInfoFactoryBean.java +++ b/dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/database/DatabaseInfoFactoryBean.java @@ -35,7 +35,7 @@ /** * @author Lars Helge Overland */ -@Component("databaseInfo") +@Component public class DatabaseInfoFactoryBean implements FactoryBean { private final DatabaseInfoProvider databaseInfoProvider; diff --git a/dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/database/HibernateDatabaseInfoProvider.java b/dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/database/HibernateDatabaseInfoProvider.java index 00e818f6f2b4..0ace43ccb460 100644 --- a/dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/database/HibernateDatabaseInfoProvider.java +++ b/dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/database/HibernateDatabaseInfoProvider.java @@ -46,7 +46,7 @@ * @author Lars Helge Overland */ @Slf4j -@Component("databaseInfoProvider") +@Component public class HibernateDatabaseInfoProvider implements DatabaseInfoProvider { private static final String EXTENSION_MISSING_ERROR = "%s extension is not installed. Execute \"CREATE EXTENSION %s;\" as a superuser and restart the application."; diff --git a/dhis-2/dhis-support/dhis-support-test/pom.xml b/dhis-2/dhis-support/dhis-support-test/pom.xml index 7729ed67959d..490fba59e3f7 100644 --- a/dhis-2/dhis-support/dhis-support-test/pom.xml +++ b/dhis-2/dhis-support/dhis-support-test/pom.xml @@ -91,6 +91,10 @@ org.hibernate hibernate-core + + javax.persistence + javax.persistence-api + org.testcontainers testcontainers diff --git a/dhis-2/dhis-support/dhis-support-test/src/main/java/org/hisp/dhis/BaseSpringTest.java b/dhis-2/dhis-support/dhis-support-test/src/main/java/org/hisp/dhis/BaseSpringTest.java index c667d5d41502..73697b4acb84 100644 --- a/dhis-2/dhis-support/dhis-support-test/src/main/java/org/hisp/dhis/BaseSpringTest.java +++ b/dhis-2/dhis-support/dhis-support-test/src/main/java/org/hisp/dhis/BaseSpringTest.java @@ -27,12 +27,13 @@ */ package org.hisp.dhis; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; import lombok.extern.slf4j.Slf4j; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.Configurator; import org.hibernate.FlushMode; -import org.hibernate.Session; -import org.hibernate.SessionFactory; +import org.hibernate.annotations.QueryHints; import org.hisp.dhis.dbms.DbmsManager; import org.hisp.dhis.external.conf.ConfigurationKey; import org.hisp.dhis.external.conf.DhisConfigurationProvider; @@ -43,8 +44,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.orm.hibernate5.SessionFactoryUtils; -import org.springframework.orm.hibernate5.SessionHolder; +import org.springframework.orm.jpa.EntityManagerFactoryUtils; +import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; @@ -118,16 +119,19 @@ protected void integrationTestBefore() throws Exception { } protected void bindSession() { - SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory"); - Session session = sessionFactory.openSession(); - session.setHibernateFlushMode(FlushMode.AUTO); - TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); + EntityManagerFactory entityManagerFactory = + (EntityManagerFactory) applicationContext.getBean("entityManagerFactory"); + EntityManager entityManager = entityManagerFactory.createEntityManager(); + entityManager.setProperty(QueryHints.FLUSH_MODE, FlushMode.AUTO); + TransactionSynchronizationManager.bindResource( + entityManagerFactory, new EntityManagerHolder(entityManager)); } protected void unbindSession() { - SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory"); - SessionHolder sessionHolder = - (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); - SessionFactoryUtils.closeSession(sessionHolder.getSession()); + EntityManagerFactory sessionFactory = + (EntityManagerFactory) applicationContext.getBean("entityManagerFactory"); + EntityManagerHolder entityManagerHolder = + (EntityManagerHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); + EntityManagerFactoryUtils.closeEntityManager(entityManagerHolder.getEntityManager()); } } diff --git a/dhis-2/dhis-test-e2e/pom.xml b/dhis-2/dhis-test-e2e/pom.xml index e628b97153a8..06bea5e36cfc 100644 --- a/dhis-2/dhis-test-e2e/pom.xml +++ b/dhis-2/dhis-test-e2e/pom.xml @@ -17,7 +17,7 @@ 2.10.1 2.21.1 5.3.2 - 2.15.3 + 2.16.0 32.1.3-jre 0.10.3 5.1.8 diff --git a/dhis-2/dhis-test-integration/pom.xml b/dhis-2/dhis-test-integration/pom.xml index 1e6ff4bc67d9..24827c33a38b 100644 --- a/dhis-2/dhis-test-integration/pom.xml +++ b/dhis-2/dhis-test-integration/pom.xml @@ -269,6 +269,11 @@ hibernate-core test + + javax.persistence + javax.persistence-api + test + com.google.code.gson gson diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/common/IdentifiableObjectManagerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/common/IdentifiableObjectManagerTest.java index cfbc97a5ad5f..ba78cab8e4aa 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/common/IdentifiableObjectManagerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/common/IdentifiableObjectManagerTest.java @@ -43,7 +43,8 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.attribute.Attribute; import org.hisp.dhis.attribute.AttributeService; import org.hisp.dhis.attribute.AttributeValue; @@ -77,7 +78,7 @@ class IdentifiableObjectManagerTest extends TransactionalIntegrationTest { private Attribute atA; - @Autowired private SessionFactory sessionFactory; + @PersistenceContext private EntityManager entityManager; @Autowired private AttributeService attributeService; @@ -404,7 +405,7 @@ void userDeniedDeleteObject() { idObjectManager.save(dataElement); dataElement.setOwner(user.getUid()); dataElement.setPublicAccess(AccessStringHelper.DEFAULT); - sessionFactory.getCurrentSession().update(dataElement); + entityManager.merge(dataElement); assertThrows(DeleteAccessDeniedException.class, () -> idObjectManager.delete(dataElement)); } @@ -432,7 +433,7 @@ void readPrivateObjects() { for (DataElement dataElement : dataElements) { dataElement.setOwner(user.getUid()); dataElement.setPublicAccess(AccessStringHelper.DEFAULT); - sessionFactory.getCurrentSession().update(dataElement); + entityManager.merge(dataElement); } assertEquals(0, idObjectManager.getCount(DataElement.class)); assertEquals(0, idObjectManager.getAll(DataElement.class).size()); diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dataapproval/DataApprovalStoreIntegrationTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dataapproval/DataApprovalStoreIntegrationTest.java index b0232f2cb44e..2c94b622ac56 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dataapproval/DataApprovalStoreIntegrationTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dataapproval/DataApprovalStoreIntegrationTest.java @@ -32,7 +32,8 @@ import com.google.common.collect.Sets; import java.util.List; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.cache.CacheProvider; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.category.CategoryOption; @@ -98,7 +99,7 @@ class DataApprovalStoreIntegrationTest extends TransactionalIntegrationTest { @Autowired private DataSetService dataSetService; - @Autowired private SessionFactory sessionFactory; + @PersistenceContext private EntityManager entityManager; @Autowired private JdbcTemplate jdbcTemplate; @@ -158,7 +159,7 @@ class DataApprovalStoreIntegrationTest extends TransactionalIntegrationTest { public void setUpTest() throws Exception { dataApprovalStore = new HibernateDataApprovalStore( - sessionFactory, + entityManager, jdbcTemplate, publisher, cacheProvider, diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dataset/LockExceptionStoreTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dataset/LockExceptionStoreTest.java index c6bc2c3fdfd3..381c4e0a7ad2 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dataset/LockExceptionStoreTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dataset/LockExceptionStoreTest.java @@ -32,7 +32,8 @@ import java.util.List; import java.util.stream.Stream; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.period.MonthlyPeriodType; @@ -49,8 +50,7 @@ class LockExceptionStoreTest extends SingleSetupIntegrationTestBase { @Autowired private PeriodStore periodStore; @Autowired private LockExceptionStore store; - - @Autowired private SessionFactory sessionFactory; + @PersistenceContext private EntityManager entityManager; private PeriodType pt; @@ -130,11 +130,10 @@ void testDeleteByOrganisationUnit() { */ private long getLockExceptionCount(OrganisationUnit target) { return (Long) - sessionFactory - .getCurrentSession() + entityManager .createQuery( "select count(*) from LockException le where le.organisationUnit = :target") .setParameter("target", target) - .uniqueResult(); + .getSingleResult(); } } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/EventImportTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/EventImportTest.java index 0e893ecba7fd..eea35c02b4bf 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/EventImportTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/EventImportTest.java @@ -50,9 +50,9 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import javax.persistence.EntityManager; import org.exparity.hamcrest.date.DateMatchers; import org.hamcrest.CoreMatchers; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.Category; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.category.CategoryOption; @@ -121,7 +121,7 @@ class EventImportTest extends TransactionalIntegrationTest { @Autowired private UserService _userService; - @Autowired private SessionFactory sessionFactory; + @Autowired private EntityManager entityManager; @Autowired JdbcTemplate jdbcTemplate; @@ -697,8 +697,8 @@ void testVerifyEventUncompleteSetsCompletedDateToNull() throws IOException { } private void cleanSession() { - sessionFactory.getCurrentSession().flush(); - sessionFactory.getCurrentSession().clear(); + entityManager.flush(); + entityManager.clear(); } private InputStream createEventsJsonInputStream( diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/ProgramStageValidationStrategyTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/ProgramStageValidationStrategyTest.java index decc318d0091..8acc81fb1107 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/ProgramStageValidationStrategyTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/ProgramStageValidationStrategyTest.java @@ -38,8 +38,8 @@ import java.util.Date; import java.util.HashSet; import java.util.stream.Stream; +import javax.persistence.EntityManager; import org.hamcrest.Matchers; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.category.CategoryOptionCombo; import org.hisp.dhis.common.CodeGenerator; @@ -89,6 +89,8 @@ class ProgramStageValidationStrategyTest extends TransactionalIntegrationTest { @Autowired private EventService programStageInstanceService; + @Autowired private EntityManager entityManager; + private TrackedEntityInstance trackedEntityInstanceMaleA; private OrganisationUnit organisationUnitA; @@ -586,10 +588,8 @@ private ImportSummary updateEvent(org.hisp.dhis.dxf2.deprecated.tracker.event.Ev return eventService.updateEvent(event, false, null, false); } - @Autowired private SessionFactory sessionFactory; - private Event getPsi(String event) { - sessionFactory.getCurrentSession().clear(); + entityManager.clear(); return programStageInstanceService.getEvent(event); } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/TrackedEntityServiceTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/TrackedEntityServiceTest.java index 9d17ad4d1eb3..c51ab031fd3f 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/TrackedEntityServiceTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/TrackedEntityServiceTest.java @@ -49,8 +49,8 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.persistence.EntityManager; import org.apache.commons.lang3.StringUtils; -import org.hibernate.SessionFactory; import org.hisp.dhis.common.CodeGenerator; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.common.Objects; @@ -113,7 +113,7 @@ class TrackedEntityServiceTest extends TransactionalIntegrationTest { @Autowired private IdentifiableObjectManager manager; - @Autowired private SessionFactory sessionFactory; + @Autowired private EntityManager entityManager; @Autowired private UserService _userService; @@ -472,7 +472,7 @@ void testUpdateTeiByCompletingExistingEnrollmentAndUpdateExistingEventsInSameEnr // This is required because the Event creation takes place using JDBC, // therefore Hibernate does not // "see" the new event in the context of this session - sessionFactory.getCurrentSession().clear(); + entityManager.clear(); trackedEntityInstance = trackedEntityInstanceService.getTrackedEntityInstance(maleA.getUid()); assertNotNull(trackedEntityInstance.getEnrollments()); assertEquals(1, trackedEntityInstance.getEnrollments().size()); @@ -535,7 +535,7 @@ void testUpdateTeiByDeletingExistingEventAndAddNewEventForSameProgramStage() { ImportStatus.SUCCESS, importSummary.getEnrollments().getImportSummaries().get(0).getEvents().getStatus()); manager.flush(); - sessionFactory.getCurrentSession().clear(); + entityManager.clear(); trackedEntityInstance = trackedEntityInstanceService.getTrackedEntityInstance(maleA.getUid()); assertNotNull(trackedEntityInstance.getEnrollments()); assertEquals(1, trackedEntityInstance.getEnrollments().size()); diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/aggregates/TrackedEntityAggregateTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/aggregates/TrackedEntityAggregateTest.java index 27d8b5850475..7e360be7f470 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/aggregates/TrackedEntityAggregateTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/aggregates/TrackedEntityAggregateTest.java @@ -52,7 +52,7 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.analytics.AggregationType; import org.hisp.dhis.common.CodeGenerator; import org.hisp.dhis.common.QueryItem; @@ -85,7 +85,7 @@ class TrackedEntityAggregateTest extends TrackerTest { @Autowired private TrackedEntityInstanceService trackedEntityInstanceService; - @Autowired private SessionFactory sessionFactory; + @Autowired private EntityManager entityManager; @Autowired private TrackedEntityProgramOwnerService programOwnerService; @@ -706,8 +706,8 @@ void testTrackedEntityInstanceRelationshipsTei2Event() { () -> { TrackedEntity t1 = this.persistTrackedEntity(); TrackedEntity t2 = this.persistTrackedEntityInstanceWithEnrollmentAndEvents(); - sessionFactory.getCurrentSession().flush(); - sessionFactory.getCurrentSession().clear(); + entityManager.flush(); + entityManager.clear(); t2 = manager.getByUid(TrackedEntity.class, Collections.singletonList(t2.getUid())).get(0); Enrollment pi = t2.getEnrollments().iterator().next(); final Event psi = pi.getEvents().iterator().next(); diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/DefaultAclStoreTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/DefaultAclStoreTest.java index d6158e28a308..0fd8fca0e1cc 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/DefaultAclStoreTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/deprecated/tracker/trackedentity/store/DefaultAclStoreTest.java @@ -45,12 +45,15 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; class DefaultAclStoreTest extends IntegrationTestBase { @Autowired private UserService _userService; - @Autowired private DefaultAclStore aclStore; + @Autowired + @Qualifier("org.hisp.dhis.dxf2.deprecated.tracker.trackedentity.store.AclStore") + private AclStore aclStore; @Autowired IdentifiableObjectManager manager; diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/metadata/MetadataImportServiceTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/metadata/MetadataImportServiceTest.java index e7d17dee5d39..f1d896aafbc9 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/metadata/MetadataImportServiceTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/metadata/MetadataImportServiceTest.java @@ -745,6 +745,7 @@ void testMetadataImportWithDeletedDataElements() throws IOException { params.setMetadataSyncImport(false); report = importService.importMetadata(params, new MetadataObjects(metadata)); assertEquals(Status.OK, report.getStatus()); + dbmsManager.flushSession(); dataset = manager.get(DataSet.class, "em8Bg4LCr5k"); assertFalse( dataset.getDataElements().stream() diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/ObjectBundleServiceTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/ObjectBundleServiceTest.java index a88e9fc79b99..17e7258f2252 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/ObjectBundleServiceTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/ObjectBundleServiceTest.java @@ -688,7 +688,6 @@ void testUpdateDataSetWithSectionsAndGreyedFields() throws IOException { ObjectBundleValidationReport validate = objectBundleValidationService.validate(bundle); assertFalse(validate.hasErrorReports()); objectBundleService.commit(bundle); - dbmsManager.clearSession(); Section section1 = manager.get(Section.class, "JwcV2ZifEQf"); assertNotNull(section1.getDataSet()); assertEquals(1, section1.getCategoryCombos().size()); @@ -710,10 +709,11 @@ void testUpdateDataSetWithSectionsAndGreyedFields() throws IOException { params.setImportStrategy(ImportStrategy.UPDATE); params.setObjects(metadata); bundle = objectBundleService.create(params); + DataElement dataElement = manager.get(DataElement.class, "nHwIqKAudKN"); + assertNotNull(dataElement); validate = objectBundleValidationService.validate(bundle); assertFalse(validate.hasErrorReports()); objectBundleService.commit(bundle); - manager.flush(); List dataSets = manager.getAll(DataSet.class); List

sections = manager.getAll(Section.class); List organisationUnits = manager.getAll(OrganisationUnit.class); diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/CompleteDataSetRegistrationBatchHandlerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/CompleteDataSetRegistrationBatchHandlerTest.java index 0a1c66996b50..cf2a368c39a5 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/CompleteDataSetRegistrationBatchHandlerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/CompleteDataSetRegistrationBatchHandlerTest.java @@ -92,11 +92,11 @@ class CompleteDataSetRegistrationBatchHandlerTest extends IntegrationTestBase { private CompleteDataSetRegistration regD; - private Date now = new Date(); + private final Date now = new Date(); - private String storedBy = "johndoe"; + private final String storedBy = "johndoe"; - private String lastUpdatedBy = "johndoe"; + private final String lastUpdatedBy = "johndoe"; // ------------------------------------------------------------------------- // Fixture @@ -165,9 +165,7 @@ public void setUpTest() { } @Override - public void tearDownTest() { - batchHandler.flush(); - } + public void tearDownTest() {} // ------------------------------------------------------------------------- // Tests diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/DataValueAuditBatchHandlerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/DataValueAuditBatchHandlerTest.java index 3eff0bd09422..1e6ac8f700db 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/DataValueAuditBatchHandlerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/DataValueAuditBatchHandlerTest.java @@ -72,8 +72,6 @@ class DataValueAuditBatchHandlerTest extends SingleSetupIntegrationTestBase { @Autowired private CategoryService categoryService; - private BatchHandler batchHandler; - private DataElement dataElementA; private CategoryOptionCombo categoryOptionComboA; @@ -107,7 +105,7 @@ class DataValueAuditBatchHandlerTest extends SingleSetupIntegrationTestBase { // ------------------------------------------------------------------------- @Override public void setUpTest() { - batchHandler = batchHandlerFactory.createBatchHandler(DataValueAuditBatchHandler.class); + dataElementA = createDataElement('A'); dataElementService.addDataElement(dataElementA); categoryOptionComboA = categoryService.getDefaultCategoryOptionCombo(); @@ -132,19 +130,18 @@ public void setUpTest() { auditB = new DataValueAudit(dataValueA, "12", storedBy, AuditType.UPDATE); auditC = new DataValueAudit(dataValueB, "21", storedBy, AuditType.UPDATE); auditD = new DataValueAudit(dataValueB, "22", storedBy, AuditType.UPDATE); - batchHandler.init(); } @Override - public void tearDownTest() { - batchHandler.flush(); - } + public void tearDownTest() {} // ------------------------------------------------------------------------- // Tests // ------------------------------------------------------------------------- @Test void testAddObject() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueAuditBatchHandler.class).init(); batchHandler.addObject(auditA); batchHandler.addObject(auditB); batchHandler.addObject(auditC); @@ -161,6 +158,8 @@ void testAddObject() { /** DataValueAudit can never equal another. */ @Test void testObjectExists() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueAuditBatchHandler.class).init(); auditService.addDataValueAudit(auditA); auditService.addDataValueAudit(auditB); assertFalse(batchHandler.objectExists(auditA)); @@ -171,6 +170,8 @@ void testObjectExists() { @Test void testUpdateObject() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueAuditBatchHandler.class).init(); auditService.addDataValueAudit(auditA); auditA.setModifiedBy("bill"); batchHandler.updateObject(auditA); diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/DataValueBatchHandlerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/DataValueBatchHandlerTest.java index e76c66da4b6f..e04fdd38e7b8 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/DataValueBatchHandlerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/jdbc/batchhandler/DataValueBatchHandlerTest.java @@ -72,8 +72,6 @@ class DataValueBatchHandlerTest extends IntegrationTestBase { @Autowired private CategoryService categoryService; - private BatchHandler batchHandler; - private DataElement dataElementA; private CategoryOptionCombo categoryOptionComboA; @@ -105,7 +103,7 @@ class DataValueBatchHandlerTest extends IntegrationTestBase { // ------------------------------------------------------------------------- @Override public void setUpTest() { - batchHandler = batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class); + dataElementA = createDataElement('A'); dataElementService.addDataElement(dataElementA); categoryOptionComboA = categoryService.getDefaultCategoryOptionCombo(); @@ -142,19 +140,19 @@ public void setUpTest() { dataElementA, periodB, unitB, categoryOptionComboA, categoryOptionComboA, "15"); // with // 4th - batchHandler.init(); + } @Override - public void tearDownTest() { - batchHandler.flush(); - } + public void tearDownTest() {} // ------------------------------------------------------------------------- // Tests // ------------------------------------------------------------------------- @Test void testInsertObject() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init(); batchHandler.insertObject(dataValueA); DataValue dataValue = dataValueService.getDataValue( @@ -164,6 +162,8 @@ void testInsertObject() { @Test void testAddObject() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init(); batchHandler.addObject(dataValueA); batchHandler.addObject(dataValueB); batchHandler.addObject(dataValueC); @@ -185,6 +185,8 @@ void testAddObject() { @Test void testAddObjectDuplicates() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init(); batchHandler.addObject(dataValueA); batchHandler.addObject(dataValueB); batchHandler.addObject(dataValueC); @@ -208,6 +210,8 @@ void testAddObjectDuplicates() { @Test void testFindObject() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init(); dataValueService.addDataValue(dataValueA); dataValueService.addDataValue(dataValueC); DataValue retrievedDataValueA = batchHandler.findObject(dataValueA); @@ -224,6 +228,8 @@ void testFindObject() { @Test void testObjectExists() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init(); dataValueService.addDataValue(dataValueA); dataValueService.addDataValue(dataValueC); assertTrue(batchHandler.objectExists(dataValueA)); @@ -235,6 +241,8 @@ void testObjectExists() { @Test @Disabled("ERROR: cannot execute UPDATE in a read-only transaction") void testUpdateObject() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init(); dataValueService.addDataValue(dataValueA); dataValueA.setValue("20"); batchHandler.updateObject(dataValueA); @@ -247,6 +255,8 @@ void testUpdateObject() { @Test void testDeleteObject() { + BatchHandler batchHandler; + batchHandler = batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init(); dataValueService.addDataValue(dataValueA); dataValueService.addDataValue(dataValueC); assertTrue(batchHandler.objectExists(dataValueA)); diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/AnalyticalObjectOrgUnitMergeHandlerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/AnalyticalObjectOrgUnitMergeHandlerTest.java index f0c805f5ce39..5ef605a92d10 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/AnalyticalObjectOrgUnitMergeHandlerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/AnalyticalObjectOrgUnitMergeHandlerTest.java @@ -29,7 +29,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.merge.orgunit.OrgUnitMergeRequest; @@ -43,7 +44,7 @@ class AnalyticalObjectOrgUnitMergeHandlerTest extends SingleSetupIntegrationTest @Autowired private IdentifiableObjectManager idObjectManager; - @Autowired private SessionFactory sessionFactory; + @PersistenceContext private EntityManager entityManager; @Autowired private AnalyticalObjectOrgUnitMergeHandler handler; @@ -100,11 +101,10 @@ void testMergeVisualizations() { */ private long getVisualizationCount(OrganisationUnit target) { return (Long) - sessionFactory - .getCurrentSession() + entityManager .createQuery( "select count(distinct v) from Visualization v where :target in elements(v.organisationUnits)") .setParameter("target", target) - .uniqueResult(); + .getSingleResult(); } } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/InterpretationDataOrgUnitMergeHandlerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/InterpretationDataOrgUnitMergeHandlerTest.java index 6667e6c05414..b3ea0708bb22 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/InterpretationDataOrgUnitMergeHandlerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/InterpretationDataOrgUnitMergeHandlerTest.java @@ -29,7 +29,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.interpretation.Interpretation; import org.hisp.dhis.interpretation.InterpretationService; @@ -55,7 +56,7 @@ class InterpretationDataOrgUnitMergeHandlerTest extends SingleSetupIntegrationTe @Autowired private DataOrgUnitMergeHandler mergeHandler; - @Autowired private SessionFactory sessionFactory; + @PersistenceContext private EntityManager entityManager; private OrganisationUnit ouA; @@ -111,10 +112,9 @@ void testMigrate() { */ private long getInterpretationCount(OrganisationUnit target) { return (Long) - sessionFactory - .getCurrentSession() + entityManager .createQuery("select count(*) from Interpretation i where i.organisationUnit = :target") .setParameter("target", target) - .uniqueResult(); + .getSingleResult(); } } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/TrackerOrgUnitMergeHandlerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/TrackerOrgUnitMergeHandlerTest.java index 2f7e90258707..7a3336928008 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/TrackerOrgUnitMergeHandlerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/merge/orgunit/handler/TrackerOrgUnitMergeHandlerTest.java @@ -30,7 +30,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.collect.Sets; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.merge.orgunit.OrgUnitMergeRequest; import org.hisp.dhis.organisationunit.OrganisationUnit; @@ -61,7 +62,7 @@ class TrackerOrgUnitMergeHandlerTest extends SingleSetupIntegrationTestBase { @Autowired private TrackerOrgUnitMergeHandler mergeHandler; - @Autowired private SessionFactory sessionFactory; + @PersistenceContext private EntityManager entityManager; private ProgramStage psA; @@ -145,10 +146,9 @@ void testMigrateEnrollments() { */ private long getEnrollmentCount(OrganisationUnit target) { return (Long) - sessionFactory - .getCurrentSession() + entityManager .createQuery("select count(*) from Enrollment pi where pi.organisationUnit = :target") .setParameter("target", target) - .uniqueResult(); + .getSingleResult(); } } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/message/MessageConversationStoreTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/message/MessageConversationStoreTest.java index f6ca23f5e135..887f144147a6 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/message/MessageConversationStoreTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/message/MessageConversationStoreTest.java @@ -34,7 +34,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; import org.hisp.dhis.test.integration.SingleSetupIntegrationTestBase; import org.hisp.dhis.user.User; import org.hisp.dhis.user.UserService; @@ -52,7 +52,7 @@ class MessageConversationStoreTest extends SingleSetupIntegrationTestBase { @Autowired private UserService _userService; - @Autowired private SessionFactory sessionFactory; + @Autowired private EntityManager entityManager; private User userB; @@ -118,7 +118,7 @@ void testGetMessageConversationsReturnsCorrectAmountOfConversations() { @Test void testGetMessageConversationsReturnCorrectNumberOfMessages() { MessageConversation conversation = messageConversationStore.get(conversationA); - sessionFactory.getCurrentSession().flush(); + entityManager.flush(); assertTrue((conversation.getMessageCount() == 4)); } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/period/PeriodServiceTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/period/PeriodServiceTest.java index a64bdd7fe32b..47016eb6bd71 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/period/PeriodServiceTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/period/PeriodServiceTest.java @@ -35,6 +35,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import javax.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.hibernate.StatelessSession; import org.hisp.dhis.test.integration.SingleSetupIntegrationTestBase; @@ -47,7 +48,7 @@ class PeriodServiceTest extends SingleSetupIntegrationTestBase { @Autowired private PeriodService periodService; - @Autowired private SessionFactory sessionFactory; + @Autowired private EntityManagerFactory entityManagerFactory; // ------------------------------------------------------------------------- // Period @@ -391,7 +392,8 @@ void testReloadPeriodInStatelessSession() { } private void removeTestPeriod(String period) { - StatelessSession session = sessionFactory.openStatelessSession(); + StatelessSession session = + entityManagerFactory.unwrap(SessionFactory.class).openStatelessSession(); session.beginTransaction(); try { session.delete(periodService.getPeriod(period)); diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramIndicatorServiceTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramIndicatorServiceTest.java index 65e8701f8383..c580f0b5aedc 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramIndicatorServiceTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramIndicatorServiceTest.java @@ -487,7 +487,7 @@ void testGetAnalyticsSQl() { @Test void testGetAnalyticsSQl2() { - String expected = "((cast(incidentdate as date) - cast(enrollmentdate as date))) / 7.0"; + String expected = "((cast(occurreddate as date) - cast(enrollmentdate as date))) / 7.0"; assertEquals( expected, programIndicatorService.getAnalyticsSql( diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramIndicatorServiceVariableTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramIndicatorServiceVariableTest.java index e825896c6640..cdea439733bc 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramIndicatorServiceVariableTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramIndicatorServiceVariableTest.java @@ -219,8 +219,8 @@ void testScheduledDate() { @Test void testIncidentDate() { - assertEquals("incidentdate", getSql("V{incident_date}")); - assertEquals("incidentdate", getSqlEnrollment("V{incident_date}")); + assertEquals("occurreddate", getSql("V{incident_date}")); + assertEquals("occurreddate", getSqlEnrollment("V{incident_date}")); } @Test diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramStageSectionIntegrationTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramStageSectionIntegrationTest.java index 9758bd7e9bd3..390a14618bac 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramStageSectionIntegrationTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/program/ProgramStageSectionIntegrationTest.java @@ -33,7 +33,8 @@ import com.google.common.collect.Sets; import java.util.HashSet; -import org.apache.commons.lang3.tuple.Pair; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementService; @@ -58,6 +59,8 @@ class ProgramStageSectionIntegrationTest extends TransactionalIntegrationTest { @Autowired private OrganisationUnitService organisationUnitService; + @PersistenceContext private EntityManager entityManager; + private Program program; private ProgramStage stageA; @@ -87,20 +90,15 @@ public void setUpTest() { @Test void testRemoveProgramStageSectionWillDeleteOrphans() { - Pair idPair = - transactionTemplate.execute( - status -> { - long idA = programStageService.saveProgramStage(stageA); - assertNotNull(programStageService.getProgramStage(idA)); - long sectionId = stageA.getProgramStageSections().stream().findFirst().get().getId(); - assertNotNull(programStageSectionService.getProgramStageSection(sectionId)); - stageA.getProgramStageSections().clear(); - programStageService.saveProgramStage(stageA); - dbmsManager.clearSession(); - return Pair.of(idA, sectionId); - }); - assertTrue( - programStageService.getProgramStage(idPair.getLeft()).getProgramStageSections().isEmpty()); - assertNull(programStageSectionService.getProgramStageSection(idPair.getRight())); + long idA = programStageService.saveProgramStage(stageA); + assertNotNull(programStageService.getProgramStage(idA)); + long sectionId = stageA.getProgramStageSections().stream().findFirst().get().getId(); + assertNotNull(programStageSectionService.getProgramStageSection(sectionId)); + stageA.getProgramStageSections().clear(); + programStageService.updateProgramStage(stageA); + dbmsManager.flushSession(); + + assertTrue(entityManager.find(ProgramStage.class, idA).getProgramStageSections().isEmpty()); + assertNull(entityManager.find(ProgramStageSection.class, sectionId)); } } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/reservedvalue/ReservedValueServiceIntegrationTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/reservedvalue/ReservedValueServiceIntegrationTest.java index 3cdbcc02ce60..95948954dcd4 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/reservedvalue/ReservedValueServiceIntegrationTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/reservedvalue/ReservedValueServiceIntegrationTest.java @@ -258,4 +258,15 @@ private static TrackedEntityAttribute createTextPattern( } return null; } + + /** + * Save reserved value and clear session to persist. In the reserved value store, the save method + * is not transactional + * + * @param reservedValue + */ + private void saveReservedValue(ReservedValue reservedValue) { + reservedValueStore.save(reservedValue); + dbmsManager.clearSession(); + } } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/reservedvalue/hibernate/HibernateReservedValueStoreTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/reservedvalue/hibernate/HibernateReservedValueStoreTest.java index 3738f7e91aa2..eb60cdf0499a 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/reservedvalue/hibernate/HibernateReservedValueStoreTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/reservedvalue/hibernate/HibernateReservedValueStoreTest.java @@ -32,7 +32,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; -import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -55,8 +54,6 @@ class HibernateReservedValueStoreTest extends SingleSetupIntegrationTestBase { - private static int counter = 1; - private static final String teaUid = "tea"; private static final String prog001 = "001"; @@ -95,12 +92,9 @@ protected void setUpTest() { @Test void reserveValuesSingleValue() { - reservedValueStore.save(reservedValue.value(prog001).build()); + saveReservedValue(reservedValue.value(prog001).build()); int count = reservedValueStore.getCount(); - ReservedValue rv = reservedValue.value(prog002).build(); - List res = - reservedValueStore.reserveValuesJpa(rv, Lists.newArrayList(rv.getValue())); - assertEquals(1, res.size()); + saveReservedValue(reservedValue.value(prog002).build()); assertEquals(reservedValueStore.getCount(), count + 1); } @@ -120,46 +114,39 @@ void isReservedShouldBeFalse() { @Test void reserveValuesMultipleValues() { - ReservedValue rv = reservedValue.value(prog001).build(); - reservedValueStore.save(rv); + saveReservedValue(reservedValue.value(prog001).build()); int count = reservedValueStore.getCount(); - ArrayList values = new ArrayList<>(); + int counter = 0; int n = 10; for (int i = 0; i < n; i++) { - values.add(String.format("%03d", counter++)); + saveReservedValue( + ReservedValue.builder() + .ownerObject(Objects.TRACKEDENTITYATTRIBUTE.name()) + .created(new Date()) + .ownerUid("FREE") + .key("00X") + .value(String.format("%03d", counter++)) + .expiryDate(futureDate) + .build()); } - List res = reservedValueStore.reserveValuesJpa(getFreeReservedValue(), values); - assertEquals(n, res.size()); - assertEquals((count + n), reservedValueStore.getCount()); - } - @Test - void reserveValuesMultipleValuesAlreadyReservedAndUsed() { - ReservedValue rv = reservedValue.value(prog001).build(); - reservedValueStore.save(rv); - int count = reservedValueStore.getCount(); - List res = - reservedValueStore.reserveValuesJpa(rv, Lists.newArrayList("002", "003", "004")); - assertEquals(1, count); - assertEquals(3, res.size()); - assertEquals((count + 3), reservedValueStore.getCount()); + assertEquals((count + counter), reservedValueStore.getCount()); } @Test void getIfReservedValuesReturnsReservedValue() { ReservedValue rv = reservedValue.value(prog001).build(); - reservedValueStore.save(rv); + saveReservedValue(rv); List res = reservedValueStore.getAvailableValues( rv, Lists.newArrayList(rv.getValue()), rv.getOwnerObject()); - assertEquals(rv, res.get(0)); - assertEquals(1, res.size()); + assertEquals(0, res.size()); } @Test void getAvailableValuesWhenNotReserved() { ReservedValue rv = reservedValue.value(prog001).build(); - reservedValueStore.save(rv); + saveReservedValue(rv); assertEquals(1, reservedValueStore.getAll().size()); List res = reservedValueStore.getAvailableValues( @@ -203,7 +190,7 @@ void removeExpiredReservations() { pastDate.add(Calendar.DATE, -1); reservedValue.expiryDate(pastDate.getTime()); ReservedValue rv = reservedValue.value(prog001).build(); - reservedValueStore.reserveValuesJpa(rv, Lists.newArrayList(rv.getValue())); + saveReservedValue(rv); assertTrue( reservedValueStore.isReserved(Objects.TRACKEDENTITYATTRIBUTE.name(), teaUid, prog001)); reservedValueStore.removeUsedOrExpiredReservations(); @@ -212,8 +199,7 @@ void removeExpiredReservations() { @Test void removeExpiredReservationsDoesNotRemoveAnythingIfNothingHasExpired() { - ReservedValue rv = reservedValue.value(prog001).build(); - reservedValueStore.save(rv); + saveReservedValue(reservedValue.value(prog001).build()); int num = reservedValueStore.getCount(); reservedValueStore.removeUsedOrExpiredReservations(); assertEquals(num, reservedValueStore.getCount()); @@ -221,8 +207,7 @@ void removeExpiredReservationsDoesNotRemoveAnythingIfNothingHasExpired() { @Test void shouldNotAddAlreadyReservedValues() { - ReservedValue rv = reservedValue.value(prog001).build(); - reservedValueStore.save(rv); + saveReservedValue(reservedValue.value(prog001).build()); OrganisationUnit ou = createOrganisationUnit("OU"); organisationUnitStore.save(ou); TrackedEntity tei = createTrackedEntity(ou); @@ -238,8 +223,7 @@ void shouldNotAddAlreadyReservedValues() { @Test void shouldRemoveAlreadyUsedReservedValues() { - ReservedValue rv = reservedValue.value(prog001).build(); - reservedValueStore.save(rv); + saveReservedValue(reservedValue.value(prog001).build()); OrganisationUnit ou = createOrganisationUnit("OU"); organisationUnitStore.save(ou); TrackedEntity tei = createTrackedEntity(ou); @@ -261,9 +245,8 @@ void shouldRemoveAlreadyUsedOrExpiredReservedValues() { // expired value Calendar pastDate = Calendar.getInstance(); pastDate.add(Calendar.DATE, -1); - reservedValueStore.reserveValuesJpa( - reservedValue.expiryDate(pastDate.getTime()).value(prog002).build(), - Lists.newArrayList(prog002)); + saveReservedValue(reservedValue.value(prog002).expiryDate(pastDate.getTime()).build()); + // used value OrganisationUnit ou = createOrganisationUnit("OU"); organisationUnitStore.save(ou); @@ -285,14 +268,14 @@ void shouldRemoveAlreadyUsedOrExpiredReservedValues() { assertEquals(0, reservedValueStore.getCount()); } - private ReservedValue getFreeReservedValue() { - return ReservedValue.builder() - .ownerObject(Objects.TRACKEDENTITYATTRIBUTE.name()) - .created(new Date()) - .ownerUid("FREE") - .key("00X") - .value(String.format("%03d", counter++)) - .expiryDate(futureDate) - .build(); + /** + * Save reserved value and clear session to persist. In the reserved value store, the save method + * is not transactional + * + * @param reservedValue + */ + private void saveReservedValue(ReservedValue reservedValue) { + reservedValueStore.save(reservedValue); + dbmsManager.clearSession(); } } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/split/orgunit/handler/AnalyticalObjectOrgUnitSplitHandlerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/split/orgunit/handler/AnalyticalObjectOrgUnitSplitHandlerTest.java index d34859d91fb4..aeb0cdb15810 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/split/orgunit/handler/AnalyticalObjectOrgUnitSplitHandlerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/split/orgunit/handler/AnalyticalObjectOrgUnitSplitHandlerTest.java @@ -29,7 +29,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.organisationunit.OrganisationUnit; @@ -46,7 +47,7 @@ class AnalyticalObjectOrgUnitSplitHandlerTest extends SingleSetupIntegrationTest @Autowired private IdentifiableObjectManager idObjectManager; - @Autowired private SessionFactory sessionFactory; + @PersistenceContext private EntityManager entityManager; @Autowired private AnalyticalObjectOrgUnitSplitHandler handler; @@ -106,11 +107,10 @@ void testSplitVisualizations() { */ private long getVisualizationCount(OrganisationUnit target) { return (Long) - sessionFactory - .getCurrentSession() + entityManager .createQuery( "select count(distinct v) from Visualization v where :target in elements(v.organisationUnits)") .setParameter("target", target) - .uniqueResult(); + .getSingleResult(); } } diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/split/orgunit/handler/DataOrgUnitSplitHandlerTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/split/orgunit/handler/DataOrgUnitSplitHandlerTest.java index 6ed4f2dd0a69..111a67221b45 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/split/orgunit/handler/DataOrgUnitSplitHandlerTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/split/orgunit/handler/DataOrgUnitSplitHandlerTest.java @@ -31,7 +31,8 @@ import com.google.common.collect.Sets; import java.util.stream.Stream; -import org.hibernate.SessionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; import org.hisp.dhis.category.CategoryOptionCombo; import org.hisp.dhis.category.CategoryService; import org.hisp.dhis.common.IdentifiableObjectManager; @@ -73,7 +74,7 @@ class DataOrgUnitSplitHandlerTest extends SingleSetupIntegrationTestBase { @Autowired private DataOrgUnitSplitHandler handler; - @Autowired private SessionFactory sessionFactory; + @PersistenceContext private EntityManager entityManager; private DataElement deA; @@ -167,20 +168,18 @@ void testMergeDataApprovals() { private long getDataValueCount(OrganisationUnit target) { return (Long) - sessionFactory - .getCurrentSession() + entityManager .createQuery("select count(*) from DataValue dv where dv.source = :target") .setParameter("target", target) - .uniqueResult(); + .getSingleResult(); } private long getDataApprovalCount(OrganisationUnit target) { return (Long) - sessionFactory - .getCurrentSession() + entityManager .createQuery("select count(*) from DataApproval da where da.organisationUnit = :target") .setParameter("target", target) - .uniqueResult(); + .getSingleResult(); } private void addDataValues(DataValue... dataValues) { diff --git a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/DefaultAclStoreTest.java b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/DefaultAclStoreTest.java index 2b521ec28354..29efd35fd9b8 100644 --- a/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/DefaultAclStoreTest.java +++ b/dhis-2/dhis-test-integration/src/test/java/org/hisp/dhis/tracker/export/trackedentity/aggregates/DefaultAclStoreTest.java @@ -45,12 +45,15 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; class DefaultAclStoreTest extends IntegrationTestBase { @Autowired private UserService _userService; - @Autowired private DefaultAclStore aclStore; + @Autowired + @Qualifier("org.hisp.dhis.tracker.trackedentity.aggregates.AclStore") + private AclStore aclStore; @Autowired IdentifiableObjectManager manager; diff --git a/dhis-2/dhis-test-web-api/pom.xml b/dhis-2/dhis-test-web-api/pom.xml index 162cc2ef550f..d66860ac7a8e 100644 --- a/dhis-2/dhis-test-web-api/pom.xml +++ b/dhis-2/dhis-test-web-api/pom.xml @@ -216,11 +216,6 @@ spring-security-core test - - org.apache.httpcomponents - httpcore - test - org.springframework.ldap spring-ldap-core diff --git a/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/DhisControllerIntegrationTest.java b/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/DhisControllerIntegrationTest.java index 512e4518a0cb..534feb02ea57 100644 --- a/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/DhisControllerIntegrationTest.java +++ b/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/DhisControllerIntegrationTest.java @@ -27,6 +27,8 @@ */ package org.hisp.dhis.webapi; +import java.time.Duration; +import java.util.function.BooleanSupplier; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.Configurator; import org.hisp.dhis.IntegrationTest; @@ -107,4 +109,14 @@ protected void integrationTestBefore() throws Exception { Configurator.setRootLevel(Level.INFO); } } + + protected static boolean await(Duration timeout, BooleanSupplier test) + throws InterruptedException { + while (!timeout.isNegative() && !test.getAsBoolean()) { + Thread.sleep(20); + timeout = timeout.minusMillis(20); + } + if (!timeout.isNegative()) return true; + return test.getAsBoolean(); + } } diff --git a/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/WebTestConfiguration.java b/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/WebTestConfiguration.java index 2b2062fc7e40..78c1d822708d 100644 --- a/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/WebTestConfiguration.java +++ b/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/WebTestConfiguration.java @@ -147,7 +147,6 @@ public DataSource actualDataSource( DatabasePoolUtils.PoolConfig.PoolConfigBuilder builder = DatabasePoolUtils.PoolConfig.builder(); builder.dhisConfig(config); - builder.hibernateConfig(hibernateConfigurationProvider); builder.dbPoolType(dbPoolType); try { diff --git a/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/controller/JobConfigurationRunErrorsControllerTest.java b/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/controller/JobConfigurationRunErrorsControllerTest.java new file mode 100644 index 000000000000..0a4971250222 --- /dev/null +++ b/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/controller/JobConfigurationRunErrorsControllerTest.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2004-2023, University of Oslo + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of the HISP project nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.hisp.dhis.webapi.controller; + +import static java.time.Duration.ofSeconds; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.function.BooleanSupplier; +import org.hisp.dhis.jsontree.JsonArray; +import org.hisp.dhis.jsontree.JsonMixed; +import org.hisp.dhis.jsontree.JsonNodeType; +import org.hisp.dhis.jsontree.JsonObject; +import org.hisp.dhis.scheduling.JobStatus; +import org.hisp.dhis.web.HttpStatus; +import org.hisp.dhis.webapi.DhisControllerIntegrationTest; +import org.hisp.dhis.webapi.json.domain.JsonJobConfiguration; +import org.hisp.dhis.webapi.json.domain.JsonWebMessage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests the job run error result API. + * + * @author Jan Bernitt + */ +class JobConfigurationRunErrorsControllerTest extends DhisControllerIntegrationTest { + + private String jobId; + + @BeforeEach + void setUp() throws InterruptedException { + jobId = createAndRunImportWithErrors(); + } + + @Test + void testGetJobRunErrors_List() { + JsonArray list = GET("/jobConfigurations/errors").content(); + + assertEquals(1, list.size()); + JsonObject job = list.getObject(0); + assertEquals(jobId, job.getString("id").string()); + assertEquals(1, job.getArray("errors").size()); + } + + @Test + void testGetJobRunErrors_ListFilterUser() { + JsonArray list = + GET("/jobConfigurations/errors?user={user}", getCurrentUser().getUid()).content(); + assertEquals(1, list.size()); + assertEquals(0, GET("/jobConfigurations/errors?user=abcde123456").content().size()); + } + + @Test + void testGetJobRunErrors_ListFilterFrom() { + assertEquals(1, GET("/jobConfigurations/errors?from=2023-01-01").content().size()); + assertEquals(0, GET("/jobConfigurations/errors?from=2033-01-01").content().size()); + } + + @Test + void testGetJobRunErrors_ListFilterTo() { + assertEquals(1, GET("/jobConfigurations/errors?to=2033-01-01").content().size()); + assertEquals(0, GET("/jobConfigurations/errors?to=2023-01-01").content().size()); + } + + @Test + void testGetJobRunErrors_ListFilterCode() { + assertEquals(1, GET("/jobConfigurations/errors?code=E4000").content().size()); + assertEquals(0, GET("/jobConfigurations/errors?code=E5000").content().size()); + } + + @Test + void testGetJobRunErrors_ListFilterType() { + assertEquals(1, GET("/jobConfigurations/errors?type=METADATA_IMPORT").content().size()); + assertEquals(0, GET("/jobConfigurations/errors?type=DATA_INTEGRITY").content().size()); + } + + @Test + void testGetJobRunErrors_Object() { + JsonObject job = GET("/jobConfigurations/{uid}/errors", jobId).content(); + assertEquals(jobId, job.getString("id").string()); + assertEquals("METADATA_IMPORT", job.getString("type").string()); + assertTrue(job.has("created", "executed", "finished", "user", "filesize", "filetype")); + assertEquals(1, job.getArray("errors").size()); + } + + @Test + void testGetJobRunErrors_ObjectProgressErrors() { + JsonArray errors = GET("/jobConfigurations/{uid}/progress/errors", jobId).content(); + assertEquals(JsonNodeType.ARRAY, errors.node().getType()); + assertEquals(1, errors.size()); + } + + private String createAndRunImportWithErrors() throws InterruptedException { + JsonWebMessage message = + POST( + "/metadata?async=true", + "{'organisationUnits':[{'name':'My Unit', 'shortName':'OU1'}]}") + .content(HttpStatus.OK) + .as(JsonWebMessage.class); + String jobId = message.getString("response.id").string(); + + BooleanSupplier jobCompleted = + () -> isDone(GET("/jobConfigurations/{id}/gist?fields=id,jobStatus", jobId).content()); + assertTrue(await(ofSeconds(10), jobCompleted), "import did not run"); + return jobId; + } + + private static boolean isDone(JsonMixed config) { + JsonJobConfiguration c = config.as(JsonJobConfiguration.class); + return c.getJobStatus() == JobStatus.COMPLETED || c.getJobStatus() == JobStatus.DISABLED; + } +} diff --git a/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/controller/TranslationWebApiTest.java b/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/controller/TranslationWebApiTest.java deleted file mode 100644 index 89efc9467a66..000000000000 --- a/dhis-2/dhis-test-web-api/src/test/java/org/hisp/dhis/webapi/controller/TranslationWebApiTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2004-2022, University of Oslo - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of the HISP project nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.hisp.dhis.webapi.controller; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.Locale; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpStatus; -import org.hisp.dhis.category.CategoryCombo; -import org.hisp.dhis.common.IdentifiableObjectManager; -import org.hisp.dhis.dataelement.DataElement; -import org.hisp.dhis.dbms.DbmsManager; -import org.hisp.dhis.translation.Translation; -import org.hisp.dhis.webapi.DhisWebSpringTest; -import org.hisp.dhis.webapi.utils.TestUtils; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * @author Viet Nguyen - */ -@Slf4j -class TranslationWebApiTest extends DhisWebSpringTest { - - @Autowired protected DbmsManager dbmsManager; - - @Autowired protected TransactionTemplate transactionTemplate; - - @Autowired private IdentifiableObjectManager identifiableObjectManager; - - @Test - @Disabled - void testOK() throws Exception { - final Locale locale = Locale.FRENCH; - final CategoryCombo categoryCombo = createCategoryCombo('C'); - final DataElement dataElementA = createDataElement('A', categoryCombo); - final String valueToCheck = "frenchTranslated"; - final MockHttpSession session = getSession("ALL"); - transactionTemplate.execute( - status -> { - identifiableObjectManager.save(categoryCombo); - identifiableObjectManager.save(dataElementA); - dataElementA - .getTranslations() - .add(new Translation(locale.getLanguage(), "NAME", valueToCheck)); - try { - mvc.perform( - put("/dataElements/" + dataElementA.getUid() + "/translations") - .session(session) - .contentType(TestUtils.APPLICATION_JSON_UTF8) - .content(TestUtils.convertObjectToJsonBytes(dataElementA))) - .andExpect(status().is(HttpStatus.SC_NO_CONTENT)); - } catch (Exception e) { - log.error("Failed:" + e.getMessage(), e); - } - dbmsManager.clearSession(); - return null; - }); - MvcResult result = - mvc.perform( - get("/dataElements/" + dataElementA.getUid() + "?locale=" + locale.getLanguage()) - .session(session) - .contentType(TestUtils.APPLICATION_JSON_UTF8)) - .andReturn(); - ObjectMapper mapper = new ObjectMapper(); - JsonNode node = mapper.readTree(result.getResponse().getContentAsString()); - assertEquals(valueToCheck, node.get("displayName").asText()); - } -} diff --git a/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/deprecated/tracker/EventController.java b/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/deprecated/tracker/EventController.java index d6247fa01596..8435541814df 100644 --- a/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/deprecated/tracker/EventController.java +++ b/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/deprecated/tracker/EventController.java @@ -59,12 +59,12 @@ import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import javax.persistence.EntityManagerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.apache.commons.lang3.StringUtils; -import org.hibernate.SessionFactory; import org.hisp.dhis.category.CategoryOptionCombo; import org.hisp.dhis.common.AssignedUserSelectionMode; import org.hisp.dhis.common.AsyncTaskExecutor; @@ -196,7 +196,7 @@ public class EventController { private final DhisConfigurationProvider dhisConfig; - private final SessionFactory sessionFactory; + private final EntityManagerFactory entityManagerFactory; private Schema schema; @@ -1199,7 +1199,7 @@ private WebMessage startAsyncImport(ImportOptions importOptions, List eve new JobConfiguration( "inMemoryEventImport", EVENT_IMPORT, currentUserService.getCurrentUser().getUid()); taskExecutor.executeTask( - new ImportEventsTask(events, eventService, importOptions, jobId, sessionFactory)); + new ImportEventsTask(events, eventService, importOptions, jobId, entityManagerFactory)); return jobConfigurationReport(jobId); } diff --git a/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/metadata/MetadataImportJob.java b/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/metadata/MetadataImportJob.java index 1aaa4126861f..4af6ddd09ca5 100644 --- a/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/metadata/MetadataImportJob.java +++ b/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/metadata/MetadataImportJob.java @@ -108,7 +108,6 @@ public void execute(JobConfiguration config, JobProgress progress) { r.getErrorCode(), r.getMainId(), r.getMainKlass().getSimpleName(), - null, r.getArgs())); } diff --git a/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/scheduling/JobConfigurationController.java b/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/scheduling/JobConfigurationController.java index 085f7f97c01a..11aae6ce13d6 100644 --- a/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/scheduling/JobConfigurationController.java +++ b/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/scheduling/JobConfigurationController.java @@ -34,15 +34,12 @@ import lombok.RequiredArgsConstructor; import org.hisp.dhis.common.IdentifiableObjects; import org.hisp.dhis.common.OpenApi; -import org.hisp.dhis.feedback.ConflictException; -import org.hisp.dhis.feedback.ForbiddenException; -import org.hisp.dhis.feedback.NotFoundException; -import org.hisp.dhis.feedback.ObjectReport; -import org.hisp.dhis.scheduling.JobConfiguration; -import org.hisp.dhis.scheduling.JobConfigurationService; -import org.hisp.dhis.scheduling.JobProgress; +import org.hisp.dhis.common.UID; +import org.hisp.dhis.feedback.*; +import org.hisp.dhis.jsontree.JsonMixed; +import org.hisp.dhis.jsontree.JsonObject; +import org.hisp.dhis.scheduling.*; import org.hisp.dhis.scheduling.JobProgress.Progress; -import org.hisp.dhis.scheduling.JobSchedulerService; import org.hisp.dhis.schema.Property; import org.hisp.dhis.schema.descriptors.JobConfigurationSchemaDescriptor; import org.hisp.dhis.user.CurrentUser; @@ -74,6 +71,25 @@ public class JobConfigurationController extends AbstractCrudController getJobRunErrors(JobRunErrorsParams params) { + return jobConfigurationService.findJobRunErrors(params); + } + + @GetMapping("{uid}/errors") + public JsonObject getJobRunErrors( + @PathVariable("uid") @OpenApi.Param({UID.class, JobConfiguration.class}) UID uid) + throws NotFoundException { + List errors = + jobConfigurationService.findJobRunErrors(new JobRunErrorsParams().setJob(uid)); + if (errors.isEmpty()) { + JobConfiguration obj = jobConfigurationService.getJobConfigurationByUid(uid.getValue()); + if (obj == null) throw new NotFoundException(JobConfiguration.class, uid.getValue()); + return JsonMixed.of("{}"); + } + return errors.get(0); + } + @GetMapping("/due") public List getDueJobConfigurations( @RequestParam int seconds, @@ -131,7 +147,7 @@ public Progress getProgress(@PathVariable("uid") String uid) { } @PreAuthorize("hasRole('ALL') or hasRole('F_PERFORM_MAINTENANCE')") - @GetMapping("{uid}/errors") + @GetMapping("{uid}/progress/errors") public List getErrors(@PathVariable("uid") String uid) { return jobSchedulerService.getErrors(uid); } diff --git a/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/servlet/DhisWebApiWebAppInitializer.java b/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/servlet/DhisWebApiWebAppInitializer.java index 77b80774be25..23fc14915803 100644 --- a/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/servlet/DhisWebApiWebAppInitializer.java +++ b/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/servlet/DhisWebApiWebAppInitializer.java @@ -40,7 +40,7 @@ import org.hisp.dhis.system.startup.StartupListener; import org.hisp.dhis.webapi.security.config.WebMvcConfig; import org.springframework.core.annotation.Order; -import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter; +import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter; import org.springframework.security.web.session.HttpSessionEventPublisher; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; @@ -104,8 +104,9 @@ public static void setupServlets( .addMappingForUrlPatterns(null, false, "/api/*"); FilterRegistration.Dynamic openSessionInViewFilter = - context.addFilter("openSessionInViewFilter", OpenSessionInViewFilter.class); - openSessionInViewFilter.setInitParameter("sessionFactoryBeanName", "sessionFactory"); + context.addFilter("openSessionInViewFilter", OpenEntityManagerInViewFilter.class); + openSessionInViewFilter.setInitParameter( + "entityManagerFactoryBeanName", "entityManagerFactory"); openSessionInViewFilter.addMappingForUrlPatterns(null, false, "/*"); openSessionInViewFilter.addMappingForServletNames(null, false, "dispatcher"); diff --git a/dhis-2/dhis-web-embedded-jetty/pom.xml b/dhis-2/dhis-web-embedded-jetty/pom.xml index 247ccfd08fca..66fcb3563c24 100644 --- a/dhis-2/dhis-web-embedded-jetty/pom.xml +++ b/dhis-2/dhis-web-embedded-jetty/pom.xml @@ -34,11 +34,6 @@ dhis-service-dxf2 jar - - org.hisp.dhis - dhis-service-core - jar - org.hisp.dhis dhis-service-administration diff --git a/dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/interceptor/ContextInterceptor.java b/dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/interceptor/ContextInterceptor.java index b101c349ab74..622a0222d862 100644 --- a/dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/interceptor/ContextInterceptor.java +++ b/dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/interceptor/ContextInterceptor.java @@ -33,13 +33,17 @@ import com.opensymphony.xwork2.interceptor.Interceptor; import java.util.HashMap; import java.util.Map; +import lombok.AllArgsConstructor; import org.apache.struts2.ServletActionContext; import org.hisp.dhis.commons.util.TextUtils; import org.hisp.dhis.system.database.DatabaseInfoProvider; +import org.springframework.stereotype.Component; /** * @author Lars Helge Overland */ +@Component +@AllArgsConstructor public class ContextInterceptor implements Interceptor { private static final String KEY_IN_MEMORY_DATABASE = "inMemoryDatabase"; @@ -49,11 +53,7 @@ public class ContextInterceptor implements Interceptor { private static final String KEY_CURRENT_KEY = "keyCurrentKey"; - private DatabaseInfoProvider databaseInfoProvider; - - public void setDatabaseInfoProvider(DatabaseInfoProvider databaseInfoProvider) { - this.databaseInfoProvider = databaseInfoProvider; - } + private final DatabaseInfoProvider databaseInfoProvider; @Override public void destroy() {} diff --git a/dhis-2/dhis-web/dhis-web-commons/src/main/resources/META-INF/dhis/beans.xml b/dhis-2/dhis-web/dhis-web-commons/src/main/resources/META-INF/dhis/beans.xml index db26bcf8c2ea..86b724c9bf45 100644 --- a/dhis-2/dhis-web/dhis-web-commons/src/main/resources/META-INF/dhis/beans.xml +++ b/dhis-2/dhis-web/dhis-web-commons/src/main/resources/META-INF/dhis/beans.xml @@ -461,10 +461,6 @@ - - - - diff --git a/dhis-2/pom.xml b/dhis-2/pom.xml index 133c5d019a62..8de8794e8348 100644 --- a/dhis-2/pom.xml +++ b/dhis-2/pom.xml @@ -89,7 +89,7 @@ 2.1.9 - 1.4.1 + 1.4.3 2.0.0 0.10.3 @@ -112,7 +112,7 @@ 2.0.7.RELEASE 2.4.1 1.6.0.Final - 6.2.6.RELEASE + 6.3.0.RELEASE 9.22.3 @@ -215,7 +215,7 @@ 2.0.9 2.2 2.0.8 - 1.19.1 + 1.19.2 1.5.1 4.2.0 2.1.18