How to link a Query to a Container?

1
TypedQuery<Empteste> minhaLista = em.createQuery("Select d from Empteste", Empteste.class);
    List<Empteste> results = minhaLista.getResultList();

I want this my list result to appear in my JPA CONTAINER I was trying this, but I did not succeed.

BeanItemContainer<Empteste> empregados = new BeanItemContainer<Empteste> (Empteste.class);
    empregados.addItem(new Empteste());
    table_1.setData(empregados);

How do I make this connection?

    
asked by anonymous 03.12.2015 / 13:53

1 answer

1

Giullia

What you are looking for is a generic DAO to be reused with several entities, follow an example

public class DAOGenerico<T> {

    private EntityManager manager;

    public DAOGenerico(EntityManager manager) {
        this.manager = manager;
    }

    public T getById(Class<T> clazz, Long id) {
        return manager.find(clazz, id);
    }

    public void save(T entity) {
        manager.getTransaction().begin();
        manager.persist(entity);
        manager.getTransaction().commit();
    }

    public void update(T entity) {
        manager.getTransaction().begin();
        manager.merge(entity);
        manager.getTransaction().commit();
    }

    public void delete(T entity) {
        manager.getTransaction().begin();
        manager.remove(entity);
        manager.getTransaction().commit();
    }

    public List<T> findAll(Class<T> type) {
        CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
        CriteriaQuery<T> query = criteriaBuilder.createQuery(type);
        Root<T> root = query.from(type);
        CriteriaQuery<T> select = query.select(root);
        TypedQuery<T> all = manager.createQuery(select);
        return all.getResultList();
    }
}

Any other class you inherit from this DAOGenerico will be able to use your methods as long as you have an EntityManager to pass.

If it is possible to inject EntityManager with EJB or CDI, even better.

    
11.12.2015 / 17:19