66 lines
1.9 KiB
Java
66 lines
1.9 KiB
Java
package com.humanbooster.dao;
|
|
|
|
import org.hibernate.Session;
|
|
import org.hibernate.SessionFactory;
|
|
|
|
import java.util.List;
|
|
|
|
public abstract class GenericDaoImpl<T, ID> implements GenericDao<T, ID> {
|
|
|
|
protected final Class<T> entityClass;
|
|
protected SessionFactory sessionFactory;
|
|
|
|
public GenericDaoImpl(SessionFactory sessionFactory, Class<T> entityClass) {
|
|
this.sessionFactory = sessionFactory;
|
|
this.entityClass = entityClass;
|
|
}
|
|
|
|
@Override
|
|
public void create(T entity) {
|
|
try (Session session = sessionFactory.openSession()) {
|
|
session.beginTransaction();
|
|
session.persist(entity);
|
|
session.getTransaction().commit();
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public T read(ID id) {
|
|
try (Session session = sessionFactory.openSession()) {
|
|
session.beginTransaction();
|
|
T entity = session.get(entityClass, id);
|
|
session.getTransaction().commit();
|
|
return entity;
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void update(T entity) {
|
|
try (Session session = sessionFactory.openSession()) {
|
|
session.beginTransaction();
|
|
session.merge(entity);
|
|
session.getTransaction().commit();
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void delete(ID id) {
|
|
try (Session session = sessionFactory.openSession()) {
|
|
session.beginTransaction();
|
|
T entity = session.find(entityClass, id);
|
|
if (entity != null) session.remove(entity);
|
|
session.getTransaction().commit();
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public List<T> findAll() {
|
|
try (Session session = sessionFactory.openSession()) {
|
|
session.beginTransaction();
|
|
List<T> entities = session.createQuery("from " + entityClass.getName(), entityClass).list();
|
|
session.getTransaction().commit();
|
|
return entities;
|
|
}
|
|
}
|
|
}
|