-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathQueryHelper.java
More file actions
49 lines (44 loc) · 2.09 KB
/
QueryHelper.java
File metadata and controls
49 lines (44 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.bobocode;
import com.bobocode.exception.QueryHelperException;
import com.bobocode.util.ExerciseNotCompletedException;
import org.hibernate.Session;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import java.util.Collection;
import java.util.function.Function;
/**
* {@link QueryHelper} provides an util method that allows to perform read operations in the scope of transaction
*/
public class QueryHelper {
private EntityManagerFactory entityManagerFactory;
public QueryHelper(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
/**
* Receives a {@link Function<EntityManager, T>}, creates {@link EntityManager} instance, starts transaction,
* performs received function and commits the transaction, in case of exception in rollbacks the transaction and
* throws a {@link QueryHelperException} with the following message: "Error performing query. Transaction is rolled back"
* <p>
* The purpose of this method is to perform read operations using {@link EntityManager}, so it uses read only mode
* by default.
*
* @param entityManagerConsumer query logic encapsulated as function that receives entity manager and returns result
* @param <T> generic type that allows to specify single entity class of some collection
* @return query result specified by type T
*/
public <T> T readWithinTx(Function<EntityManager, T> entityManagerConsumer) {
var entityManager = entityManagerFactory.createEntityManager();
entityManager.unwrap(Session.class).setDefaultReadOnly(true);
entityManager.getTransaction().begin();
try {
T result = entityManagerConsumer.apply(entityManager);
entityManager.getTransaction().commit();
return result;
} catch (Exception e) {
entityManager.getTransaction().rollback();
throw new QueryHelperException("Transaction is rolled back.", e);
} finally {
entityManager.close();
}
}
}