com.bookselling.dao.GenericDao.java Source code

Java tutorial

Introduction

Here is the source code for com.bookselling.dao.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 com.bookselling.dao;

import com.bookselling.CRUDOperation;
import com.bookselling.util.PaginationData;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author Phan Phat
 */
public abstract class GenericDao<T> implements CRUDOperation<T> {
    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void add(T obj) {
        getSession().save(obj);
    }

    @Override
    public void delete(T obj) {
        getSession().delete(obj);
    }

    @Override
    public void delete(T[] obj) {
        for (T e : obj)
            getSession().delete(e);
    }

    @Override
    public void update(T obj) {
        getSession().update(obj);
    }

    @Override
    public void merge(T obj) {
        getSession().merge(obj);
    }

    @Override
    public List<T> get() {
        List<T> entities = getSession().createCriteria(registeredClass()).list();
        HibernateInitSupport.setCls(registeredClass());
        for (T e : entities)
            HibernateInitSupport.initDomain((T) e);
        return entities;
    }

    @Override
    public T get(Serializable id) {
        Object obj = getSession().get(registeredClass(), id);
        HibernateInitSupport.setCls(registeredClass());
        HibernateInitSupport.initDomain((T) obj);
        return (T) obj;
    }

    @Override
    public PaginationData get(int first, int items) {
        Criteria criteria = getSession().createCriteria(registeredClass());
        criteria.setFirstResult(first);
        criteria.setMaxResults(items);
        List<T> entities = criteria.list();
        HibernateInitSupport.setCls(registeredClass());
        for (T e : entities)
            HibernateInitSupport.initDomain((T) e);

        PaginationData paginationData = new PaginationData(count(), items, first, entities);
        return paginationData;
    }

    @Override
    public long count() {
        return (long) getSession().createCriteria(registeredClass()).setProjection(Projections.rowCount())
                .uniqueResult();
    }

    public abstract Class<T> registeredClass();
}