Package au.edu.uts.aip.mandreacchio.ejb

Source Code of au.edu.uts.aip.mandreacchio.ejb.ItemDAOJpaImpl

package au.edu.uts.aip.mandreacchio.ejb;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import au.edu.uts.aip.mandreacchio.jpa.Item;

public class ItemDAOJpaImpl implements ItemDAO {

  @PersistenceContext
  private EntityManager em;

  // this is the default constructor
  public ItemDAOJpaImpl() {
    this("store");
  }

  public ItemDAOJpaImpl(String unitName) {
    EntityManagerFactory emf = Persistence
        .createEntityManagerFactory(unitName);
    em = emf.createEntityManager();
  }

  // this is the special constructor to set the entity manager.
  // this is used when we run with EJB3
  public ItemDAOJpaImpl(EntityManager em) {
    this.em = em;
  }

  public void setEntityManager(EntityManager em) {
    this.em = em;
  }

  // Begin Methods
  @Override
  public List<Item> getAllItems(int maxResults, int offset) {
   
    Query query = em.createQuery("select i from Item i order by LOWER(i.description)");
    query.setMaxResults(maxResults);
    query.setFirstResult(offset);
   
    @SuppressWarnings("unchecked")
    List<Item> results = query.getResultList();
    return results;
  }

  @Override
  public List<Item> getItemsByCategory(String category, int maxResults, int offset) {
   
    Query query = em.createQuery("SELECT i FROM Item i INNER JOIN i.itemcategory c WHERE c.category = ?1 ORDER BY LOWER(i.description)");
    query.setParameter(1, category);
    query.setMaxResults(maxResults);
    query.setFirstResult(offset);

    @SuppressWarnings("unchecked")
    List<Item> results = query.getResultList();
    return results;
  }

  @Override
  public Item getItemById(int id) {
    @SuppressWarnings("unchecked")
    Item result = em.find(Item.class, id);
    return result;
  }

  @Override
  public int getAllItemsCount() {
    @SuppressWarnings("unchecked")
    int count = ((Long)em.createQuery("select count(i) from Item i").getSingleResult()).intValue();
    return count;
  }

  @Override
  public int getItemCountByCategory(String category) {
    int count = ((Long)em.createQuery("SELECT count(i) FROM Item i INNER JOIN i.itemcategory c WHERE c.category = ?1")
          .setParameter(1, category).getSingleResult()).intValue();
    return count;
  }

}
TOP

Related Classes of au.edu.uts.aip.mandreacchio.ejb.ItemDAOJpaImpl

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.