view src/main/java/de/intevation/lada/data/Repository.java @ 182:a2e04ab2cd44

Use the new filter and query builder and have authentication for LProbeInfo objects.
author Raimund Renkert <rrenkert@intevation.de>
date Thu, 27 Jun 2013 15:03:18 +0200
parents f33f6e1ba9f8
children 253160854d79
line wrap: on
line source
package de.intevation.lada.data;

import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import de.intevation.lada.rest.Response;

/**
 * This generic Container is an interface to request and select Data
 * obejcts from the connected database.
 * 
 * @author <a href="mailto:rrenkert@intevation.de">Raimund Renkert</a>
 */
@RequestScoped
public abstract class Repository
{
    /**
     * The entitymanager managing the data.
     */
    @Inject
    private EntityManager em;

    public abstract Response create(Object object);

    public abstract Response update(Object object);

    /**
     * Filter object list by the given criteria.
     *
     * @param criteria
     * @return List of objects.
     */
    public <T> Response filter(CriteriaQuery<T> filter) {
        List<T> result = em.createQuery(filter).getResultList();
        return new Response(true, 200, result);
    }


    /**
     * Get all objects of type <link>clazz</link>from database.
     *
     * @param clazz The class type.
     * @return List of objects.
     */
    public <T> Response findAll(Class<T> clazz) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<T> criteria = builder.createQuery(clazz);
        Root<T> member = criteria.from(clazz);
        criteria.select(member);
        List<T> result = em.createQuery(criteria).getResultList();
        return new Response(true, 200, result);
    }

    /**
     * Find a single object identified by its id.
     * 
     * @param clazz The class type.
     * @param id The object id.
     * @return The requested object of type clazz
     */
    public <T> Response findById(Class<T> clazz, String id) {
        T item = em.find(clazz, id);
        if (item == null) {
            return new Response(false, 600, null);
        }
        return new Response(true, 200, item);
    }

    public EntityManager getEntityManager() {
        return this.em;
    }
}
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)