Search code examples
javaspringjpaentitymanager

How to return a set of persisted objects?


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
}

Solution

  • 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());
    }