com.askme.dao.AnswerDAOImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.askme.dao.AnswerDAOImpl.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.Answer;
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 AnswerDAOImpl implements AnswerDAO {

    @Autowired
    private SessionFactory sessionFactory;

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

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

    @Override
    public void save(Answer answer) {
        sessionFactory.getCurrentSession().save(answer);
    }

    @Override
    public void delete(Answer answer) {
        sessionFactory.getCurrentSession().delete(answer);
    }

    @Override
    public void upVotes(Answer answer) {
        sessionFactory.getCurrentSession().createQuery("update Answer a set a.votes = a.votes + 1 where a.id = :id")
                .setParameter("id", answer.getId()).executeUpdate();
    }

    @Override
    public void downVotes(Answer answer) {
        sessionFactory.getCurrentSession().createQuery("update Answer a set a.votes = a.votes - 1 where a.id = :id")
                .setParameter("id", answer.getId()).executeUpdate();
    }

    @Override
    public void updateBest(Answer answer) {
        sessionFactory.getCurrentSession().createQuery("update Answer a set a.best = 1 where a.id = :id")
                .setParameter("id", answer.getId()).executeUpdate();
    }

    @Override
    public void resetBest(Answer answer) {
        sessionFactory.getCurrentSession()
                .createQuery("update Answer a set a.best = 0 where a.question = :question")
                .setParameter("question", answer.getQuestion()).executeUpdate();
    }

}