JPA (Java Persistence API) in Eclipse

Introduction

Let's make a JPA sample program in Eclipse. Modify MVC program and use JPA to get data from Postgre SQL DB. Create an Emplyee table in advance. (See: Install Postgre SQL)

Development environment

Windows 10 Pro 1709(16299.192) Eclipse pleiades-4.7.3 java 1.8.0_162 PostgreSQL 10.4 Released!

procedure

    1. Download PostgreSQL JDBC Driver
  1. Copy to WEB-INF \ lib of project

    1. Create a connection to Postgres SQL
  2. Convert to JPA project

  3. Source code changes

  4. Operation check

1. 1. Download PostgreSQL JDBC Driver

URL

https://jdbc.postgresql.org/download.html

1. Click "PostgreSQL JDBC 4.2 Driver, 42.2.2"

image.png

2. Copy to WEB-INF \ lib of project

image.png

3. 3. Create a connection to Postgres SQL

1. Select "Window"-> "View View"-> "Other" menu

image.png

2. Select "Data Management" "Data Source Explorer" and click "Open"

image.png

3. Click "New" on the right menu on "Data Source Connection"

image.png

4. Select Postgres SQL and click Next

image.png

5. Enter "Database", "URL", "Username" and "Password" and click "Test Connection".

6. Confirm "Ping completed successfully" and click the "OK" button.

7. Click the "Finish" button

image.png

8. You can see the table created in Install Postgre SQL

image.png

4. Convert to JPA project

1. Select Right Menu-> Configuration-> Convert to JPA Project on the project

image.png

2. Click "Next"

image.png

3. Select "EclipseLink 2.5.2" and click "Next"

image.png

4. Check "Accept the terms of this license" and click "Finish"

image.png

5. Select the "New PostgreSQL" connection, check "Build Path", "Override Default Catalog from Connection", "Override Default Schema from Connection", and click "Finish".

image.png

6. Select Right Menu-> JPA Tools-> Generate Entity from Table on Project

image.png

7. Check the "employee" table and click "Finish"

image.png

5. Source code changes

1. Add @NamedQuery of findById to Employee Entity

Change before

@Entity
@NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable {
After change

@Entity
@NamedQueries({
	@NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e"),
	@NamedQuery(name = "Employee.findById", query = "SELECT e from Employee e where e.id = :id")
})
public class Employee implements Serializable {

2. Changed to get EmployeeServlet from DB

After change

package emp;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Employee;


/**
 * Servlet implementation class EmployeeServlet
 */
@WebServlet(name = "EmpList", urlPatterns = { "/EmpList" })
public class EmployeeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmployeeServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		EntityManagerFactory emf = Persistence.createEntityManagerFactory("SampleMVC2");
		EntityManager entityManager = emf.createEntityManager();

        List<Employee> employeeList = entityManager
                .createNamedQuery("Employee.findAll", Employee.class)
                .getResultList();

        entityManager.close();
        emf.close();


	    //Pass Model data to View
	    request.setAttribute("employeeList", employeeList);

	    //Show View
	    this.getServletContext()
	        .getRequestDispatcher("/employeeList.jsp")
	        .forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		EntityManagerFactory emf = Persistence.createEntityManagerFactory("SampleMVC2");
		EntityManager entityManager = emf.createEntityManager();

		List<Employee> employeeList;

		String id = request.getParameter("id");

		if (id.isEmpty()) {
	        employeeList = entityManager
	                .createNamedQuery("Employee.findAll", Employee.class)
	                .getResultList();
		}
		else {
	        employeeList = entityManager
	                .createNamedQuery("Employee.findById", Employee.class)
	                .setParameter("id", id)
	                .getResultList();
		}

        entityManager.close();
        emf.close();

        //Pass Model data to View
		request.setAttribute("employeeList", employeeList);


		//Show View
	    this.getServletContext()
	        .getRequestDispatcher("/employeeList.jsp")
	        .forward(request, response);

	}

}

3. Right menu on Employee Bean-> Select "Delete"

image.png

4. Select "OK"

image.png

5. Change "persistence.xml"

Change before

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="SampleMVC">
		<class>model.Employee</class>
	</persistence-unit>
</persistence>
After change (DB connection information added)

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="SampleMVC2">
		<class>model.Employee</class>
		<properties>
			<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" /> <!-- DB Driver -->
			<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/postgres" /> <!-- BD Mane -->
			<property name="javax.persistence.jdbc.user" value="postgres" /> <!-- DB User -->
			<property name="javax.persistence.jdbc.password" value="dev" /> <!-- DB Password -->
		</properties>
	</persistence-unit>
</persistence>

6. Operation check

[Refer to "MVC with Eclipse." Operation check](https://qiita.com/0ashina0/items/7c378823905949b301af#4-%E5%8B%95%E4%BD%9C%E7%A2%BA%E8% AA% 8D)

in conclusion

--The annotation @PersistenceContext can be added to EntityManager only when transaction management (container management) is performed. Otherwise @PersistenceContext is ignored.

Recommended Posts

JPA (Java Persistence API) in Eclipse
[Java] API creation using Jerjey (Jax-rs) in eclipse
Null-safe program in Java (Eclipse)
First Java development in Eclipse
Try running Selenuim 3.141.59 in eclipse (java)
Hit Zaim's API (OAuth 1.0) in Java
Parsing the COTOHA API in Java
I tried using Elasticsearch API in Java
Implement API Gateway Lambda Authorizer in Java Lambda
Studying Java 8 (date API in java.time package)
Try using the Stream API in Java
Call the Windows Notification API in Java
Try using JSON format API in Java
[Java] Set AdoptOpen JDK in STS (Eclipse)
Play Framework 2.6 (Java) environment construction in Eclipse
Partization in Java
Rock-paper-scissors in Java
Java Stream API
MVC in Eclipse.
Pi in Java
FizzBuzz in Java
ChatWork4j for using the ChatWork API in Java
Technology for reading Java source code in Eclipse
Try using GCP's Cloud Vision API in Java
Try using the COTOHA API parsing in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
I tried Mastodon's Toot and Streaming API in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
Java (eclipse) installation procedure
Eclipse ~ Java project creation ~
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Pack API response (java)
Callable Interface in Java
Call Amazon Product Advertising API 5.0 (PA-API v5) in Java
I tried using Google Cloud Vision API in Java
[Java] Stream API / map
Azure functions in java
Docker-Client Java API Troubleshooting
Simple htmlspecialchars in Java
To debug in eclipse
Boyer-Moore implementation in Java
Hello World in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
How to Git manage Java EE projects in Eclipse
Create JSON in Java
Date manipulation in Java 8