Обновление ECI, репозитории, девайсы

This commit is contained in:
RoyceDa
2026-02-03 02:28:46 +02:00
parent c22d2de4be
commit 4c290a01ac
19 changed files with 513 additions and 359 deletions

View File

@@ -0,0 +1,158 @@
package com.rosetta.im.database;
import java.util.HashMap;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
* Базовый репозиторий для работы с сущностями базы данных
*/
public abstract class Repository<T> {
protected Class<T> entityClass;
public Repository(Class<T> entityClass) {
this.entityClass = entityClass;
}
public T save(T entity) {
return executeInTransaction(session -> {
session.persist(entity);
return entity;
});
}
public T update(T entity) {
return executeInTransaction(session -> {
session.merge(entity);
return entity;
});
}
public void delete(T entity) {
executeInTransaction(session -> {
session.remove(entity);
return null;
});
}
/**
* Поиск сущности по значению одного поля
* @param fieldName поле
* @param value значение
* @return найденная сущность или null
*/
public T findByField(String fieldName, Object value) {
return executeInSession(session -> {
String queryString = "FROM " + entityClass.getSimpleName() + " WHERE " + fieldName + " = :value";
return session.createQuery(queryString, entityClass)
.setParameter("value", value)
.uniqueResult();
});
}
/**
* Поиск сущности по набору полей
* @param fields карта полей и их значений
* @return найденная сущность или null
*/
public T findByField(HashMap<String, Object> fields) {
return executeInSession(session -> {
StringBuilder queryString = new StringBuilder("FROM " + entityClass.getSimpleName() + " WHERE ");
int index = 0;
for (String fieldName : fields.keySet()) {
if (index > 0) {
queryString.append(" AND ");
}
queryString.append(fieldName).append(" = :").append(fieldName);
index++;
}
var query = session.createQuery(queryString.toString(), this.entityClass);
for (var entry : fields.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
return query.uniqueResult();
});
}
public void update(HashMap<String, Object> fieldsToUpdate, HashMap<String, Object> whereFields) {
executeInTransaction(session -> {
StringBuilder queryString = new StringBuilder("UPDATE " + entityClass.getSimpleName() + " SET ");
int index = 0;
for (String fieldName : fieldsToUpdate.keySet()) {
if (index > 0) {
queryString.append(", ");
}
queryString.append(fieldName).append(" = :").append(fieldName);
index++;
}
queryString.append(" WHERE ");
index = 0;
for (String fieldName : whereFields.keySet()) {
if (index > 0) {
queryString.append(" AND ");
}
/**
* Добавляем префикс where_ к параметрам условия WHERE,
* чтобы избежать конфликтов имен с параметрами SET
*/
queryString.append(fieldName).append(" = :where_").append(fieldName);
index++;
}
var query = session.createQuery(queryString.toString(), this.entityClass);
for (var entry : fieldsToUpdate.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
for (var entry : whereFields.entrySet()) {
/**
* Устанавливаем параметры с префиксом where_ для условий WHERE,
* чтобы избежать конфликтов имен с параметрами SET
*/
query.setParameter("where_" + entry.getKey(), entry.getValue());
}
query.executeUpdate();
return null;
});
}
protected <R> R executeInTransaction(TransactionCallback<R> callback) {
Session session = HibernateUtil.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
R result = callback.execute(session);
transaction.commit();
return result;
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
throw new RuntimeException("Transaction failed: " + e.getMessage(), e);
} finally {
session.close();
}
}
protected <R> R executeInSession(SessionCallback<R> callback) {
try (Session session = HibernateUtil.openSession()) {
return callback.execute(session);
}
}
/**
* Функциональный интерфейс для обратного вызова транзакции.
* (Коллбэки)
*/
@FunctionalInterface
protected interface TransactionCallback<R> {
R execute(Session session);
}
@FunctionalInterface
protected interface SessionCallback<R> {
R execute(Session session);
}
}