Java tutorial
/* * This file is part of EasyExchange. * * (c) 2014 - Machiel Molenaar <machiel@machiel.me> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.mtech.easyexchange.dao.impl; import com.mtech.easyexchange.dao.AbstractDao; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import java.io.Serializable; import java.util.List; public class AbstractDaoImpl<T, ID extends Serializable> implements AbstractDao<T, ID> { protected Class<T> entityClass; protected SessionFactory sessionFactory; protected AbstractDaoImpl(Class<T> entityClass, Session session) { this.entityClass = entityClass; this.sessionFactory = session.getSessionFactory(); } @Override public Session getCurrentSession() { return sessionFactory.getCurrentSession(); } @Override @SuppressWarnings("unchecked") public T find(ID id) { Transaction tx = getCurrentSession().beginTransaction(); T result = (T) getCurrentSession().get(entityClass, id); tx.commit(); return result; } @Override public void save(T entity) { Transaction tx = getCurrentSession().beginTransaction(); getCurrentSession().saveOrUpdate(entity); tx.commit(); } @Override public void delete(T entity) { Transaction tx = getCurrentSession().beginTransaction(); getCurrentSession().delete(entity); tx.commit(); } @Override @SuppressWarnings("unchecked") public List<T> findBy(Criterion... criterions) { Transaction tx = getCurrentSession().beginTransaction(); Criteria criteria = getCurrentSession().createCriteria(entityClass); for (Criterion criterion : criterions) { criteria.add(criterion); } List<T> result = (List<T>) criteria.list(); tx.commit(); return result; } @Override @SuppressWarnings("unchecked") public T findOneBy(Criterion... criterions) { Transaction tx = getCurrentSession().beginTransaction(); Criteria criteria = getCurrentSession().createCriteria(entityClass); for (Criterion criterion : criterions) { criteria.add(criterion); } T result = (T) criteria.uniqueResult(); tx.commit(); return result; } }