/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ejb;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author zwergnase
 */
@Stateless
public class TrainsFacade {
    @PersistenceContext(unitName = "NewsApp-ejbPU")
    private EntityManager em;

    public void create(Trains trains) {
        em.persist(trains);
    }

    public void edit(Trains trains) {
        em.merge(trains);
    }

    public void remove(Trains trains) {
        em.remove(em.merge(trains));
    }

    public Trains find(Object id) {
        return em.find(Trains.class, id);
    }

    public List<Trains> findAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Trains.class));
        return em.createQuery(cq).getResultList();
    }

    public List<Trains> findRange(int[] range) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Trains.class));
        Query q = em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<Trains> rt = cq.from(Trains.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}
