Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider adding convenience methods for wrapping transactions in Java SE environments #204

Closed
fwgreen opened this issue Jan 24, 2019 · 1 comment

Comments

@fwgreen
Copy link

fwgreen commented Jan 24, 2019

Performing simple operations in Java SE environments has a lot of ceremony and the risk of getting it wrong. I'm proposing adding some convenience methods to reduce both code bloat and guess work from the users end. Here is my current approach:

public static void transaction(EntityManagerFactory emf, Consumer<EntityManager> operation) {
    var em = emf.createEntityManager();
    try {
	em.getTransaction().begin();
	operation.accept(em);
	em.getTransaction().commit();
    } catch (Throwable t1) {
	try {
	    em.getTransaction().rollback();
	} catch (Throwable t2) {
	    t2.printStackTrace();
	}
	throw t1;
    } finally {
	em.close();
    }
}
	
public static <E> E transaction(EntityManagerFactory emf, Function<EntityManager, E> operation) {
    var em = emf.createEntityManager();
    try {
	em.getTransaction().begin();
	E result = operation.apply(em);
	em.getTransaction().commit();
	return result;
    } catch (Throwable t1) {
	try {
	    em.getTransaction().rollback();
	} catch (Throwable t2) {
	    t2.printStackTrace();
	}
	throw t1;
    } finally {
	em.close();
    }
}

which allows me to use JPA like this:

public E update(E entity) {
    return transaction(emf, (EntityManager em) -> em.merge(entity));
}
	
public void save(E entity) {
    transaction(emf, (EntityManager em) -> em.persist(entity));
}
@gavinking
Copy link
Contributor

Apologies, @fwgreen, I opened #410 as a dupe of this one. That was my bad.

(The issue title wasn't very clear, so I missed it.)

When #414 is done, we can close this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants