com.askme.dao.CategoryDAOImpl.java Source code

Java tutorial

Introduction

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

import com.askme.model.Category;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Admin
 */
@Repository
public class CategoryDAOImpl implements CategoryDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    @Override
    public List<Category> findAll() {
        List<Category> categories = sessionFactory.getCurrentSession().createQuery("from Category").list();
        for (Category category : categories) {
            long questionsSize = (Long) sessionFactory.getCurrentSession()
                    .createFilter(category.getQuestions(), "select count(*)").uniqueResult();
            category.setQuestionsSize(questionsSize);
        }
        return categories;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Category findById(int id) {
        return (Category) sessionFactory.getCurrentSession().get(Category.class, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Category findByName(String name) {
        List<Category> categories = sessionFactory.getCurrentSession()
                .createQuery("from Category where name = :name").setParameter("name", name).list();

        return (categories.isEmpty()) ? null : categories.get(0);
    }

    @Override
    public Long countAll() {
        return (Long) sessionFactory.getCurrentSession().createCriteria(Category.class)
                .setProjection(Projections.rowCount()).uniqueResult();
    }

    @Override
    public void save(Category category) {
        sessionFactory.getCurrentSession().save(category);
    }

    @Override
    public void update(Category category) {
        sessionFactory.getCurrentSession().update(category);
    }

    @Override
    public void delete(Category category) {
        sessionFactory.getCurrentSession().delete(category);
    }

}