de.inetsource.jsfforum.db.ThreadFacade.java Source code

Java tutorial

Introduction

Here is the source code for de.inetsource.jsfforum.db.ThreadFacade.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 de.inetsource.jsfforum.db;

import de.inetsource.jsfforum.entity.Forum;
import de.inetsource.jsfforum.entity.Post;
import de.inetsource.jsfforum.entity.Thread;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Joerg Wiesmann joerg.wiesmann@gmail.com
 */
@Service
public class ThreadFacade extends AbstractFacade<Thread> {

    @PersistenceContext(unitName = "forumPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ThreadFacade() {
        super(Thread.class);
    }

    public List<Thread> findArticlesFromTopic(Integer forumId) {
        Query query = getEntityManager().createNamedQuery("Thread.findByForumId");
        query.setParameter("id", new Forum(forumId));
        return query.getResultList();
    }

    public int countThreadsByForum(Forum forumId) {
        String SQL = "SELECT count(thread) FROM Thread thread WHERE thread.forumId = :forumId";
        javax.persistence.Query q = getEntityManager().createQuery(SQL);
        q.setParameter("forumId", forumId);
        return ((Long) q.getSingleResult()).intValue();
    }

    public Post getLastPost(Thread t) {
        return getPost(t, true);
    }

    public Post getFirstPost(Thread t) {
        return getPost(t, false);
    }

    private Post getPost(Thread t, boolean last) {
        try {
            String sort = "asc";
            if (last) {
                sort = "desc";
            }
            Query q = em.createQuery("SELECT p FROM Post p where p.threadId = :thread order by p.created " + sort,
                    Post.class);
            q.setParameter("thread", t);
            q.setMaxResults(1);
            return (Post) q.getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
    }

    @Override
    @Transactional
    public void edit(Thread entity) {
        super.edit(entity);
    }
}