Configuring JPA

Now, let’s add a dependency for MySQL in the project. Refer to Figure 4.11 in Chapter 4, Creating JEE Database Applications, for adding a Maven dependency for the MySQL JDBC driver, or simply add the following dependency to pom.xml:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.8-dmr</version>
</dependency>

Convert the project to a JPA project so that we can use the JPA tooling provided by Eclipse. Right-click on the project in the Project Explorer and select the Configure | Convert to JPA Project option. Make sure the following Project Facets are selected, along with the default facets:

  • Dynamic Web Module
  • JAX-RS (RESTful web services)
  • JPA

Click the Next button (refer to Figure 4.20 Add JPA facet to the project of Chapter 4, Creating JEE Database Applications) and configure the JPA facet as shown in Figure 4.21. Click Finish.

Let’s now configure the JDBC connection in persistence.xml. Follow steps 7 through 9 in the Converting project into a JPA project section in Chapter 4, Creating JEE Database Applications. Your persistence.xml should now have the following persistence unit:

<persistence-unit name="coursemanagement" transaction-type="RESOURCE_LOCAL">
<properties>
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>packt.book.jeeeclipse.wildflyswarm.coursemanagement.rest.Course</class>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/course_management"/>
<property name="javax.persistence.jdbc.user" value="<enter_your_user_name> "/>
<property name="javax.persistence.jdbc.password" value="<enter_your_password> "/>
</properties>
</persistence-unit>

In the previous XML file, we are specifying the org.eclipse.persistence.jpa.PersistenceProvider class as our JPA provider and then setting properties for connecting to the MySQL database.

Next, create folders named resources/META-INF under src/main and copy persistence.xml into the src/main/resources folder. If Eclipse displays errors in JPA configuration, right-click on the project name in Project Explorer and select Maven | Update Project. The reason for doing this is that Maven expects files that you want to copy to the classes folder to be in the src/main/resources folder. We need to have META-INF/persistence.xml in the classes folder so that the JPA provider can load it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.111.179