ash.resourcemanager.hibernate.GenericDAO.java Source code

Java tutorial

Introduction

Here is the source code for ash.resourcemanager.hibernate.GenericDAO.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ash.resourcemanager.hibernate;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;

/**
 *
 * @author Ash
 */
public class GenericDAO<T> {

    private Class<T> _type;
    private Session _currentSession;

    public GenericDAO(Class<T> type) {
        _type = type;
    }

    public Integer create(T o) {
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        Integer result = (Integer) session.save(o);
        transaction.commit();
        return result;
    }

    public T getById(Integer id) {
        return (T) getSession().get(_type, id);
    }

    public List<T> getRange(Integer startId, Integer endId) {
        ArrayList<T> values = new ArrayList<T>();
        if (startId < endId) {
            for (Integer i = startId; i <= endId; i++) {
                T value = this.getById(i);
                values.add(value);
            }
        }
        return values;
    }

    public List<T> getAll() {
        return getSession().createCriteria(_type).list();
    }

    public void update(T o) {
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        session.update(o);
        transaction.commit();
    }

    public void delete(T o) {
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        getSession().delete(o);
        transaction.commit();
    }

    public List<T> getWithCriterion(Criterion criterion) {
        Session session = getSession();
        Transaction transaction = session.beginTransaction();

        List<T> entities = session.createCriteria(_type).add(criterion).list();

        transaction.commit();

        return entities;
    }

    private SessionFactory getSessionFactory() {
        return HibernateUtil.getSessionFactory();
    }

    private Session getSession() {
        if (_currentSession == null) {
            _currentSession = getSessionFactory().openSession();
        }
        return _currentSession;
    }
}