Enterprise Java Development@TOPIC@

Chapter 34. JPA Entity Exercise Setup

34.1. Setup Maven Project

The setup for this exercise will use a maven archetype process to build you the shell of a JPA module to perform these exercises. The module can be created anywhere, but if you create it within a directory that already has a pom.xml, the archetype will attempt to integrate the new module as a sub-module of the existing parent.

TEST YOUTUBE LINK

  • Add the following to your .m2/settings.xml file. This will allow you to resolve the exercise archetype and set a default database for the exercise.

        <profiles>
           <profile>
                <id>webdev-repositories</id>
                <repositories>
                    <repository>
                        <id>webdev</id>
                        <name>ejava webdev repository</name>
                        <url>http://webdev.jhuep.com/~jcs/maven2</url>
                        <releases>
                            <enabled>true</enabled>
                            <updatePolicy>never</updatePolicy>
                        </releases>
                        <snapshots>
                            <enabled>false</enabled>
                        </snapshots>
                    </repository>
                    <repository>
                        <id>webdev-snapshot</id>
                        <name>ejava webdev snapshot repository</name>
                        <url>http://webdev.jhuep.com/~jcs/maven2-snapshot</url>
                        <releases>
                            <enabled>false</enabled>
                        </releases>
                        <snapshots>
                            <enabled>true</enabled>
                            <updatePolicy>daily</updatePolicy>
                        </snapshots>
                    </repository>
                </repositories>
            </profile>
        </profiles>
        <activeProfiles>
            <activeProfile>h2db</activeProfile>
            <!--
            <activeProfile>h2srv</activeProfile>
            -->
        </activeProfiles>
    
  • Use the ejava.jpa:jpa-archetype to setup a new Maven project for this exercise. Activate the webdev-repositories profile (-Pwebdev-repositories) so that you can resolve the archetype off the Internet. The following should be run outside of the class example tree.

    $ mvn archetype:generate -B -DarchetypeGroupId=info.ejava.examples.jpa -DarchetypeArtifactId=jpa-archetype -DarchetypeVersion=5.0.0-SNAPSHOT -DgroupId=myorg.relex -DartifactId=relationEx -Pwebdev-repositories
    [INFO] Scanning for projects...
    ...
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating project from Archetype: jpa-archetype:5.0.0-SNAPSHOT
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: myorg.relex
    [INFO] Parameter: artifactId, Value: relationEx
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: myorg.relex
    [INFO] Parameter: packageInPathFormat, Value: myorg/relex
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: myorg.relex
    [INFO] Parameter: groupId, Value: myorg.relex
    [INFO] Parameter: artifactId, Value: relationEx
    [INFO] Project created from Archetype in dir: /Users/jim/proj/784/relationEx
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 2.287 s
    [INFO] Finished at: 2018-08-18T12:19:05-04:00
    [INFO] Final Memory: 18M/314M
    [INFO] ------------------------------------------------------------------------
    
  • You should now have an instantiated template for a JPA project

    relationEx/
    ├── pom.xml
    └── src
        ├── main
        │   └── java
        │       └── myorg
        │           └── relex
        │               └── Auto.java
        └── test
            ├── java
            │   └── myorg
            │       └── relex
            │           └── AutoTest.java
            └── resources
                ├── hibernate.properties
                ├── log4j.xml
                └── META-INF
                    └── persistence.xml
    
  • Verify the instantiated template builds in your environment

    • Activate the h2db profile (and deactivate the h2srv profile) to use an embedded file as your database. This option does not require a server but is harder to inspect database state in between tests.

      relationEx]$ mvn clean test -Ph2db -P\!h2srv
      ...
       -HHH000401: using driver [org.h2.Driver] at URL [jdbc:h2:/Users/jim/proj/784/relationEx/target/h2db/ejava]
      ...
      [INFO] ------------------------------------------------------------------------
      [INFO] BUILD SUCCESS
      [INFO] ------------------------------------------------------------------------
      
    • Start your database server

      $ java -jar M2_REPO/com/h2database/h2/1.4.197/h2-1.4.197.jar
      
    • Activate the h2srv profile (and deactivate the h2db profile) to use a running H2 database server. This option provides more interaction with your database but does require the server to be running.

      relationEx]$ mvn clean test -P\!h2db -Ph2srv
      ...
       -HHH000401: using driver [org.h2.Driver] at URL [jdbc:h2:tcp://127.0.0.1:9092/./h2db/ejava]
      ...
      [INFO] ------------------------------------------------------------------------
      [INFO] BUILD SUCCESS
      [INFO] ------------------------------------------------------------------------
      
  • You may now import the instantiated template into Eclipse as an "Existing Maven Project"

  • Put the following Junit test case in your src/test tree

    
    
    package myorg.relex;
    import javax.persistence.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.junit.*;
    public class JPATestBase {
        private static Logger log = LoggerFactory.getLogger(JPATestBase.class);
        private static final String PERSISTENCE_UNIT = "relationEx-test";
        private static EntityManagerFactory emf;
        protected EntityManager em;    
        @BeforeClass
        public static void setUpClass() {
            log.debug("creating entity manager factory");
            emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
        }
        
        @Before
        public void setUp() throws Exception {
            log.debug("creating entity manager");
            em = emf.createEntityManager();
            cleanup();
            em.getTransaction().begin();
        }
        @After
        public void tearDown() throws Exception {
            logger.debug("tearDown() started, em={}", em);
            if (em!=null) {
                EntityTransaction tx = em.getTransaction();
                if (tx.isActive()) {
                    if (tx.getRollbackOnly() == true) { tx.rollback(); }
                    else                              { tx.commit(); }
                } else {
                    tx.begin();
                    tx.commit();
                }
                em.close();
                em=null;
            }
            logger.debug("tearDown() complete, em={}", em);
         }
        
        @AfterClass
        public static void tearDownClass() {
            log.debug("closing entity manager factory");
            if (emf!=null) { emf.close(); }
        }
        
        public void cleanup() {
            em.getTransaction().begin();
            em.getTransaction().commit();
        }
        protected EntityManager createEm() {
            return emf.createEntityManager();
        }
    }