-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseRepositoryImpl.java
More file actions
428 lines (381 loc) · 15.2 KB
/
BaseRepositoryImpl.java
File metadata and controls
428 lines (381 loc) · 15.2 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package jazzyframework.data;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import jakarta.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Logger;
/**
* Default implementation of BaseRepository using Hibernate SessionFactory.
*
* <p>This class provides concrete implementations for all CRUD operations
* defined in BaseRepository interface. It uses Hibernate Session for
* database operations and handles transactions automatically.
*
* <p>Key features:
* <ul>
* <li>Automatic transaction management</li>
* <li>Generic type resolution for entity operations</li>
* <li>Efficient batch operations</li>
* <li>Proper exception handling and logging</li>
* </ul>
*
* @param <T> the entity type
* @param <ID> the type of the entity's primary key
*
* @since 0.3.0
* @author Caner Mastan
*/
public class BaseRepositoryImpl<T, ID> implements BaseRepository<T, ID> {
private static final Logger logger = Logger.getLogger(BaseRepositoryImpl.class.getName());
protected final SessionFactory sessionFactory;
protected final Class<T> entityClass;
protected final Class<ID> idClass;
protected final String entityName;
protected final String idFieldName;
/**
* Creates a new BaseRepositoryImpl with the given SessionFactory and entity types.
*
* @param sessionFactory the Hibernate SessionFactory
* @param entityClass the entity class
* @param idClass the ID class
*/
public BaseRepositoryImpl(SessionFactory sessionFactory, Class<T> entityClass, Class<ID> idClass) {
this.sessionFactory = sessionFactory;
this.entityClass = entityClass;
this.idClass = idClass;
this.entityName = entityClass.getSimpleName();
this.idFieldName = findIdFieldName();
}
/**
* Creates a new BaseRepositoryImpl with automatic type resolution.
* This constructor is used when the repository is created through reflection.
*
* @param sessionFactory the Hibernate SessionFactory
*/
@SuppressWarnings("unchecked")
public BaseRepositoryImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
// Resolve generic types from the class hierarchy
Type[] actualTypeArguments = getActualTypeArguments();
this.entityClass = (Class<T>) actualTypeArguments[0];
this.idClass = (Class<ID>) actualTypeArguments[1];
this.entityName = entityClass.getSimpleName();
this.idFieldName = findIdFieldName();
}
/**
* Gets the actual type arguments for the generic types.
*/
private Type[] getActualTypeArguments() {
Type genericSuperclass = getClass().getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
return parameterizedType.getActualTypeArguments();
}
throw new IllegalStateException("Cannot resolve generic types for " + getClass());
}
/**
* Finds the ID field name using @Id annotation.
*/
private String findIdFieldName() {
Field[] fields = entityClass.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Id.class)) {
return field.getName();
}
}
return "id"; // fallback to default
}
@Override
public T save(T entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity must not be null");
}
try {
return executeInTransaction(session -> session.merge(entity));
} catch (Exception e) {
logger.severe("Error saving entity: " + e.getMessage());
throw new RuntimeException("Failed to save entity", e);
}
}
@Override
public List<T> saveAll(Iterable<T> entities) {
if (entities == null) {
throw new IllegalArgumentException("Entities must not be null");
}
List<T> savedEntities = new ArrayList<>();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
for (T entity : entities) {
if (entity == null) {
throw new IllegalArgumentException("Entity must not be null");
}
T savedEntity = session.merge(entity);
savedEntities.add(savedEntity);
}
transaction.commit();
return savedEntities;
} catch (Exception e) {
logger.severe("Error saving entities: " + e.getMessage());
throw new RuntimeException("Failed to save entities", e);
}
}
@Override
public Optional<T> findById(ID id) {
if (id == null) {
throw new IllegalArgumentException("ID must not be null");
}
try {
return executeInTransaction(session -> Optional.ofNullable(session.get(entityClass, id)));
} catch (Exception e) {
logger.severe("Error finding entity by ID: " + e.getMessage());
throw new RuntimeException("Failed to find entity", e);
}
}
@Override
public boolean existsById(ID id) {
if (id == null) {
throw new IllegalArgumentException("ID must not be null");
}
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
Query<Long> query = session.createQuery(
"SELECT COUNT(e) FROM " + entityName + " e WHERE e." + idFieldName + " = :id", Long.class);
query.setParameter("id", id);
Long count = query.uniqueResult();
transaction.commit();
return count != null && count > 0;
} catch (Exception e) {
logger.severe("Error checking entity existence: " + e.getMessage());
throw new RuntimeException("Failed to check entity existence", e);
}
}
@Override
public List<T> findAll() {
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
Query<T> query = session.createQuery("FROM " + entityName, entityClass);
List<T> entities = query.list();
transaction.commit();
return entities;
} catch (Exception e) {
logger.severe("Error finding all entities: " + e.getMessage());
throw new RuntimeException("Failed to find entities", e);
}
}
@Override
public List<T> findAllById(Iterable<ID> ids) {
if (ids == null) {
throw new IllegalArgumentException("IDs must not be null");
}
List<ID> idList = new ArrayList<>();
ids.forEach(idList::add);
if (idList.isEmpty()) {
return new ArrayList<>();
}
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
Query<T> query = session.createQuery(
"FROM " + entityName + " e WHERE e." + idFieldName + " IN (:ids)", entityClass);
query.setParameterList("ids", idList);
List<T> entities = query.list();
transaction.commit();
return entities;
} catch (Exception e) {
logger.severe("Error finding entities by IDs: " + e.getMessage());
throw new RuntimeException("Failed to find entities", e);
}
}
@Override
public long count() {
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
Query<Long> query = session.createQuery("SELECT COUNT(e) FROM " + entityName + " e", Long.class);
Long count = query.uniqueResult();
transaction.commit();
return count != null ? count : 0L;
} catch (Exception e) {
logger.severe("Error counting entities: " + e.getMessage());
throw new RuntimeException("Failed to count entities", e);
}
}
@Override
public void deleteById(ID id) {
if (id == null) {
throw new IllegalArgumentException("ID must not be null");
}
try {
executeInTransactionVoid(session -> {
T entity = session.get(entityClass, id);
if (entity != null) {
session.remove(entity);
}
});
logger.fine("Deleted entity with ID: " + id);
} catch (Exception e) {
logger.severe("Error deleting entity by ID: " + e.getMessage());
throw new RuntimeException("Failed to delete entity", e);
}
}
@Override
public void delete(T entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity must not be null");
}
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
session.remove(entity);
transaction.commit();
logger.fine("Deleted entity: " + entityName);
} catch (Exception e) {
logger.severe("Error deleting entity: " + e.getMessage());
throw new RuntimeException("Failed to delete entity", e);
}
}
@Override
public void deleteAllById(Iterable<ID> ids) {
if (ids == null) {
throw new IllegalArgumentException("IDs must not be null");
}
List<ID> idList = new ArrayList<>();
ids.forEach(idList::add);
if (idList.isEmpty()) {
return;
}
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
var query = session.createMutationQuery(
"DELETE FROM " + entityName + " e WHERE e." + idFieldName + " IN (:ids)");
query.setParameterList("ids", idList);
int deletedCount = query.executeUpdate();
transaction.commit();
logger.fine("Deleted " + deletedCount + " entities by IDs");
} catch (Exception e) {
logger.severe("Error deleting entities by IDs: " + e.getMessage());
throw new RuntimeException("Failed to delete entities", e);
}
}
@Override
public void deleteAll(Iterable<T> entities) {
if (entities == null) {
throw new IllegalArgumentException("Entities must not be null");
}
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
for (T entity : entities) {
if (entity != null) {
session.remove(entity);
}
}
transaction.commit();
logger.fine("Deleted entities of type: " + entityName);
} catch (Exception e) {
logger.severe("Error deleting entities: " + e.getMessage());
throw new RuntimeException("Failed to delete entities", e);
}
}
@Override
public void deleteAll() {
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
var query = session.createMutationQuery("DELETE FROM " + entityName);
int deletedCount = query.executeUpdate();
transaction.commit();
logger.fine("Deleted all " + deletedCount + " entities of type: " + entityName);
} catch (Exception e) {
logger.severe("Error deleting all entities: " + e.getMessage());
throw new RuntimeException("Failed to delete all entities", e);
}
}
@Override
public void flush() {
try (Session session = sessionFactory.openSession()) {
session.flush();
} catch (Exception e) {
logger.severe("Error flushing session: " + e.getMessage());
throw new RuntimeException("Failed to flush session", e);
}
}
@Override
public T saveAndFlush(T entity) {
T savedEntity = save(entity);
flush();
return savedEntity;
}
@Override
public void deleteInBatch(Iterable<T> entities) {
if (entities == null) {
throw new IllegalArgumentException("Entities must not be null");
}
List<ID> ids = new ArrayList<>();
for (T entity : entities) {
if (entity != null) {
try {
Field idField = entityClass.getDeclaredField(idFieldName);
idField.setAccessible(true);
@SuppressWarnings("unchecked")
ID id = (ID) idField.get(entity);
if (id != null) {
ids.add(id);
}
} catch (Exception e) {
logger.warning("Could not extract ID from entity: " + e.getMessage());
}
}
}
deleteAllById(ids);
}
@Override
public void deleteAllInBatch() {
deleteAll();
}
/**
* Helper method to execute operations in a transaction with proper rollback handling.
*
* @param operation the operation to execute
* @param <R> the return type
* @return the result of the operation
*/
protected <R> R executeInTransaction(Function<Session, R> operation) {
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
try {
R result = operation.apply(session);
transaction.commit();
return result;
} catch (Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
throw e;
}
}
}
/**
* Helper method to execute void operations in a transaction with proper rollback handling.
*
* @param operation the operation to execute
*/
protected void executeInTransactionVoid(Consumer<Session> operation) {
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
try {
operation.accept(session);
transaction.commit();
} catch (Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
throw e;
}
}
}
}