|
| 1 | +package com.baeldung.jpa.stringcast; |
| 2 | + |
| 3 | +import org.junit.BeforeClass; |
| 4 | +import org.junit.Test; |
| 5 | + |
| 6 | +import javax.persistence.EntityManager; |
| 7 | +import javax.persistence.EntityManagerFactory; |
| 8 | +import javax.persistence.EntityTransaction; |
| 9 | +import javax.persistence.Persistence; |
| 10 | +import java.util.List; |
| 11 | + |
| 12 | +import static org.junit.Assert.assertEquals; |
| 13 | + |
| 14 | +public class SpringCastTest { |
| 15 | + |
| 16 | + private static EntityManager em; |
| 17 | + private static EntityManagerFactory emFactory; |
| 18 | + |
| 19 | + @BeforeClass |
| 20 | + public static void setup() { |
| 21 | + emFactory = Persistence.createEntityManagerFactory("jpa-h2"); |
| 22 | + em = emFactory.createEntityManager(); |
| 23 | + |
| 24 | + // insert an object into the db |
| 25 | + DummyEntity dummyEntity = new DummyEntity(); |
| 26 | + dummyEntity.setText("text"); |
| 27 | + |
| 28 | + EntityTransaction tr = em.getTransaction(); |
| 29 | + tr.begin(); |
| 30 | + em.persist(dummyEntity); |
| 31 | + tr.commit(); |
| 32 | + } |
| 33 | + |
| 34 | + @Test(expected = ClassCastException.class) |
| 35 | + public void givenExecutorNoCastCheck_whenQueryReturnsOneColumn_thenClassCastThrown() { |
| 36 | + List<String[]> results = QueryExecutor.executeNativeQueryNoCastCheck("select text from dummy", em); |
| 37 | + |
| 38 | + // fails |
| 39 | + for (String[] row : results) { |
| 40 | + // do nothing |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + @Test |
| 45 | + public void givenExecutorWithCastCheck_whenQueryReturnsOneColumn_thenNoClassCastThrown() { |
| 46 | + List<String[]> results = QueryExecutor.executeNativeQueryWithCastCheck("select text from dummy", em); |
| 47 | + assertEquals("text", results.get(0)[0]); |
| 48 | + } |
| 49 | + |
| 50 | + @Test |
| 51 | + public void givenExecutorGeneric_whenQueryReturnsOneColumn_thenNoClassCastThrown() { |
| 52 | + List<DummyEntity> results = QueryExecutor.executeNativeQueryGeneric("select text from dummy", "textQueryMapping", em); |
| 53 | + assertEquals("text", results |
| 54 | + .get(0) |
| 55 | + .getText()); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments