|
| 1 | +/* |
| 2 | + * Hibernate, Relational Persistence for Idiomatic Java |
| 3 | + * |
| 4 | + * License: GNU Lesser General Public License (LGPL), version 2.1 or later. |
| 5 | + * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. |
| 6 | + */ |
| 7 | +package org.hibernate.jpa.test.transaction; |
| 8 | + |
| 9 | +import java.util.List; |
| 10 | +import java.util.Map; |
| 11 | +import javax.persistence.Entity; |
| 12 | +import javax.persistence.EntityManager; |
| 13 | +import javax.persistence.EntityTransaction; |
| 14 | +import javax.persistence.GeneratedValue; |
| 15 | +import javax.persistence.Id; |
| 16 | + |
| 17 | +import org.hibernate.cfg.AvailableSettings; |
| 18 | +import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; |
| 19 | + |
| 20 | +import org.junit.Test; |
| 21 | + |
| 22 | +import static org.hamcrest.core.Is.is; |
| 23 | +import static org.junit.Assert.assertThat; |
| 24 | + |
| 25 | +/** |
| 26 | + * @author Andrea Boriero |
| 27 | + */ |
| 28 | +public class JtaReusingEntityTransactionTest extends BaseEntityManagerFunctionalTestCase { |
| 29 | + |
| 30 | + @Override |
| 31 | + protected Class<?>[] getAnnotatedClasses() { |
| 32 | + return new Class[] { TestEntity.class }; |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + protected void addConfigOptions(Map options) { |
| 37 | + super.addConfigOptions( options ); |
| 38 | + options.put( AvailableSettings.JPA_TRANSACTION_TYPE, "JTA" ); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void entityTransactionShouldBeReusableTest() { |
| 43 | + EntityManager em = createEntityManager(); |
| 44 | + EntityTransaction transaction = null; |
| 45 | + try { |
| 46 | + transaction = em.getTransaction(); |
| 47 | + em.persist( new TestEntity() ); |
| 48 | + transaction.begin(); |
| 49 | + transaction.commit(); |
| 50 | + transaction.begin(); |
| 51 | + em.persist( new TestEntity() ); |
| 52 | + transaction.commit(); |
| 53 | + } |
| 54 | + finally { |
| 55 | + if ( transaction != null && transaction.isActive() ) { |
| 56 | + transaction.rollback(); |
| 57 | + } |
| 58 | + em.close(); |
| 59 | + } |
| 60 | + em = createEntityManager(); |
| 61 | + try { |
| 62 | + transaction = em.getTransaction(); |
| 63 | + transaction.begin(); |
| 64 | + List<TestEntity> results = em.createQuery( "from TestEntity" ).getResultList(); |
| 65 | + assertThat( results.size(), is( 2 ) ); |
| 66 | + transaction.commit(); |
| 67 | + } |
| 68 | + finally { |
| 69 | + if ( transaction != null && transaction.isActive() ) { |
| 70 | + transaction.rollback(); |
| 71 | + } |
| 72 | + em.close(); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + @Entity(name = "TestEntity") |
| 77 | + public static class TestEntity { |
| 78 | + @Id |
| 79 | + @GeneratedValue |
| 80 | + private Long id; |
| 81 | + } |
| 82 | +} |
| 83 | + |
0 commit comments