Suppose I have an EJB, CrudService, with methods to perform CRUD on a single entity (so not collections). CrudService has an EntityManager injected into it, and it cannot be modified. CrudService looks something like this:
@Stateless
public class CrudService {
@PersistenceContext(name = "TxTestPU")
private EntityManager em;
public Integer createPost(Post post) {
post = em.merge(post);
return post.getId();
}
public void updatePost(Post post) {
em.merge(post);
}
public Post readPost(Integer id) {
return em.find(Post.class, id);
}
public void deletePost(Post post) {
em.remove(post);
}
}
I would like to be able to create/update a collection of Post entities, in parallel, in a single transaction. An approach which does not work, as for each thread in the pool a new transaction is created by the container, is the following :
@Stateless
public class BusinessBean {
@Inject
private CrudService crudService;
public void savePosts(Collection<Post> posts) {
posts.parallelStream().forEach(post ->
crudService.createPost(post);
}
}
Is there a way to do it ? The code runs on Wildfly, with a Hibernate persistence unit and Postgresql database.