How to connect a Query to a Container?

Asked

Viewed 51 times

1

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

I want that my list result to appear in my JPA CONTAINER I was trying so, 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 that call?

  • Giullia, what do you mean by JPA Container? This is from some specific framework?

1 answer

1

Giullia

What you’re looking for is a generic DAO to be reused with multiple entities, here’s 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 make use of your methods, as long as you have an Entitymanager to pass.

If you can inject Entitymanager with EJB or CDI, even better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.