|
| 1 | +package org.javaee7.jpa.nativesql; |
| 2 | + |
| 3 | +import org.jboss.arquillian.container.test.api.Deployment; |
| 4 | +import org.jboss.arquillian.junit.Arquillian; |
| 5 | +import org.jboss.shrinkwrap.api.ShrinkWrap; |
| 6 | +import org.jboss.shrinkwrap.api.spec.WebArchive; |
| 7 | +import org.junit.Test; |
| 8 | +import org.junit.runner.RunWith; |
| 9 | + |
| 10 | +import javax.inject.Inject; |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +import static org.junit.Assert.assertEquals; |
| 14 | +import static org.junit.Assert.assertFalse; |
| 15 | + |
| 16 | +/** |
| 17 | + * In this sample we're going to query a simple +JPA Entity+, using the +JPA EntityManager Native Query+ and perform |
| 18 | + * a select operation. |
| 19 | + * |
| 20 | + * include::Employee[] |
| 21 | + * |
| 22 | + * The select operation is very simple. We just need to call the API method +createNativeQuery+ on the +EntityManager+. |
| 23 | + * |
| 24 | + * include::EmployeeBean[]#get |
| 25 | + * |
| 26 | + * @author Roberto Cortez |
| 27 | + */ |
| 28 | +@RunWith(Arquillian.class) |
| 29 | +public class JpaNativeSqlTest { |
| 30 | + @Inject |
| 31 | + private EmployeeBean employeeBean; |
| 32 | + |
| 33 | + /** |
| 34 | + * We're just going to deploy the application as a +web archive+. Note the inclusion of the following files: |
| 35 | + * |
| 36 | + * [source,file] |
| 37 | + * ---- |
| 38 | + * /META-INF/persistence.xml |
| 39 | + * /META-INF/create.sql |
| 40 | + * /META-INF/drop.sql |
| 41 | + * /META-INF/load.sql |
| 42 | + * ---- |
| 43 | + * |
| 44 | + * The +persistence.xml+ file is needed of course for the persistence unit definition. A datasource is not |
| 45 | + * needed, since we can now use the new default datasource available in +JEE7+. We're also using the new |
| 46 | + * +javax.persistence.schema-generation.*+ propertires to create, populate and drop the database. |
| 47 | + */ |
| 48 | + @Deployment |
| 49 | + public static WebArchive createDeployment() { |
| 50 | + WebArchive war = ShrinkWrap.create(WebArchive.class) |
| 51 | + .addPackage("org.javaee7.jpa.nativesql") |
| 52 | + .addAsResource("META-INF/persistence.xml") |
| 53 | + .addAsResource("META-INF/create.sql") |
| 54 | + .addAsResource("META-INF/drop.sql") |
| 55 | + .addAsResource("META-INF/load.sql"); |
| 56 | + System.out.println(war.toString(true)); |
| 57 | + return war; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * In the test, we're just going to invoke the only available operation in the +EmployeeBean+ and assert a few |
| 62 | + * details to confirm that the native query was successfully executed. |
| 63 | + */ |
| 64 | + @Test |
| 65 | + public void testNativeSql() { |
| 66 | + List<Employee> employees = employeeBean.get(); |
| 67 | + assertFalse(employees.isEmpty()); |
| 68 | + assertEquals(8, employees.size()); |
| 69 | + } |
| 70 | +} |
0 commit comments