Question

I have a class with a method for creating a customer object via entity manager. I want to add another method which will return a set of created objects; how can I do that in my case? For instance, I have the following code:

public class DefaultCoreRepository implements CoreRepository {

private EntityManager entityManager;

@PersistenceContext(unitName = "crm-db")
public void setEntityManager(EntityManager entityManager) {
    this.entityManager = entityManager;
}

private <T> T persist(T entity) {
    entityManager.persist(entity);
    return entity;
}

public void createCustomer(Customer customer) {
    persist(customer);
}

public Set<Customer> getCustomers() {
    //Code to be written here
}
Was it helpful?

Solution 2

You can write a query like this and convert List to Set:

public Set<Customer> getCustomers() {
     return new HashSet<Customer>(createQuery("select c from Customer c", Customer.class).getResultList());
}

OTHER TIPS

Since JPA 2.2 you can also use the Java 8 stream API:

entityManager.createQuery("SELECT customer FROM Customer customer", Customer.class)
            .getResultStream()
            .collect(Collectors.toSet());

One possible way could be

entityManager.createQuery("SELECT customer FROM Customer customer",  
                          Customer.class) 
             .getResultList();

You can create select queries in your entity manager to get result lists using the JPA

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top