Tuesday 2 July 2019

JPA: Hello World Application


In this post, you are going to learn,
a.   Setting up JPA project in Eclipse
b.   How to map simple Employee class to Employee table of RDBMS,
c.    How to insert the Employee object to Employee table using JPA.
d.   How to connect to the database using DBVisualizer and see the data of Employee table.

Setting up JPA project in Eclipse
Open Eclipse. Create new maven project.


Select the checkbox ‘Create a simple project (Skip archetype selection)’.


Click on Next button.


Give the Group Id, Artifact Id as jpaDemp, Version as 1 and click on Finish button.

Project created like below.



Add dependencies to pom.xml file.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>jpaDemo</groupId>
 <artifactId>jpaDemo</artifactId>
 <version>1</version>

 <dependencies>
  <!-- https://mvnrepository.com/artifact/org.eclipse.persistence/eclipselink -->
  <dependency>
   <groupId>org.eclipse.persistence</groupId>
   <artifactId>eclipselink</artifactId>
   <version>2.7.1</version>
   <exclusions>
    <exclusion>
     <groupId>org.eclipse.persistence</groupId>
     <artifactId>javax.persistence</artifactId>
    </exclusion>
   </exclusions>
  </dependency>

  <!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
  <dependency>
   <groupId>javax.persistence</groupId>
   <artifactId>javax.persistence-api</artifactId>
   <version>2.2</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/org.apache.derby/derbyclient -->
  <dependency>
   <groupId>org.apache.derby</groupId>
   <artifactId>derbyclient</artifactId>
   <version>10.14.2.0</version>
  </dependency>

 </dependencies>
</project>

How to map simple Employee class to Employee table of RDBMS,
Create Employee class like below.


Employee.java
package com.sample.myApp.entities;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {

 @Id
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}

@Entity specifies that the class Employee is an entity. The entity class must have a no-arg constructor. The no-arg constructor must be public or protected.

Create META-INF directory under src/main/resources. Place persistence.xml file under META-INF directory.


persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
 xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
 <persistence-unit name="myPersistenceUnit"
  transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

  <class>com.sample.myApp.entities.Employee</class>

  <properties>
   <property name="eclipselink.target-database" value="Derby" />
   <property name="javax.persistence.jdbc.driver"
    value="org.apache.derby.jdbc.ClientDriver" />
   <property name="javax.persistence.jdbc.url"
    value="jdbc:derby://localhost:1527/demoDatabase;create=true" />
   <property name="javax.persistence.jdbc.user" value="APP" />
   <property name="javax.persistence.jdbc.password" value="APP" />
   <property name="eclipselink.logging.level" value="INFO" />

   <property name="eclipselink.ddl-generation"
    value="drop-and-create-tables" />

   <property name="eclipselink.ddl-generation.output-mode"
    value="database" />
  </properties>

 </persistence-unit>
</persistence>

Do not worry much about this configuration. I will explain more about this in my later posts. In brief, it contains the information to connect to the database (like username, password, database server url, database name etc.,),  Entity classes (classes that are mapped to a table), logging details etc.,

Below table summarizes the properties.
Property
Value
Description
eclipselink.target-database
Derby
It specifies the database to use. Since I am using Apache Derby in my application, the value is Derby here.

At the time of writing this article, below are the valid values for this property.

Attunity
Auto (Default): EclipseLink attempts to access the database and the JDBC metadata to determine the target database.
Cloudscape
Database: Use a generic database, if your target database is not listed and your JDBC driver does not support the metadata required for Auto.
DB2
DB2Mainframe
DBase
Derby
HSQL
Informix
JavaDB
MaxDB
MySQL
MySQL4
Oracle
Oracle10
Oracle11
Oracle8
Oracle9
PointBase
PostgreSQL
SQLAnywhere
SQLServer
Sybase
Symfoware
TimesTen
javax.persistence.jdbc.driver
org.apache.derby.jdbc.ClientDriver
Specifies the fully qualified name of the jdbc driver. Since I am using derby here ‘org.apache.derby.jdbc.ClientDriver’ is the client driver I should use.
javax.persistence.jdbc.url
jdbc:derby://localhost:1527/demoDatabase;create=true
Driver specific url.

jdbc:derby
The JDBC protocol specification for the Derby driver.

Localhost:1527
Server and port details, where the Derby server is running.

demoDatabase
The name of the database. Since no filepath is specified, the database is created in the default working directory (From where you ran the derby server).

;create=true
Create attribute is used to create a database. Derby does not have an SQL ‘create database’ command.
javax.persistence.jdbc.user
APP
Username used to connect to the database server.
javax.persistence.jdbc.password
APP
Password used to connect to the database server.
eclipselink.logging.level
INFO
specify a specific logging level and control the amount and detail EclipseLink writes to the log. In this example, I set the log level to INFO.

Possible values are OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL
eclipselink.ddl-generation
drop-and-create-tables
Specify how EclipseLink generates DDL (Data Definition Language) for the database schema (tables and constraints) on deployment

Possible values are:
create-tables: EclipseLink will attempt to execute a CREATE TABLE SQL for each table.

create-or-extend-tables: EclipseLink will attempt to create tables. If the table exists, EclipseLink will add any missing columns.

drop-and-create-tables: EclipseLink will attempt to DROP all tables, then CREATE all tables.

none: (Default) No DDL generated; no schema generated.
eclipselink.ddl-generation.output-mode

Specify where EclipseLink generates and writes the DDL.

Possible values are.

sql-script: DDL will be generated and written to a file only.
database: DL will be generated and written to the database only.

both: DDL will be generated and written to both the database and a file.

Persistence Unit
<persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL">
         .....
         .....
</persistence-unit>

A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application. In the above example, I defined a persistence unit with name myPersistenceUnit.


How to insert the Employee object to Employee table using JPA?

TestApp.java
package com.sample.myApp.entities;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class TestApp {

 public static void main(String args[]) {
  EntityManagerFactory emf = null;
  EntityManager em = null;

  try {
   emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

   em = emf.createEntityManager();

   Employee emp = new Employee();
   emp.setFirstName("Krishna");
   emp.setLastName("Gurram");
   emp.setId(1);

   em.getTransaction().begin();
   em.persist(emp);
   em.getTransaction().commit();

   Query q = em.createQuery("select e from Employee e", Employee.class);
   List<Employee> emps = q.getResultList();
   for (Employee emp1 : emps) {
    System.out.println(emp1);
   }
  } finally {
   if (em != null && em.isOpen()) {
    em.close();
   }

   if (emf != null && emf.isOpen()) {
    emf.close();
   }
  }

 }

}


When you ran TestApp.java, you can able to see below messages in console.

[EL Info]: 2018-06-24 22:37:49.462--ServerSession(707976812)--EclipseLink, version: Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f
[EL Info]: connection: 2018-06-24 22:37:49.586--ServerSession(707976812)--/file:/C:/Users/Krishna/java9/jpaDemo/target/classes/_myPersistenceUnit login successful
Employee [id=1, firstName=Krishna, lastName=Gurram]
[EL Info]: connection: 2018-06-24 22:37:49.939--ServerSession(707976812)--/file:/C:/Users/Krishna/java9/jpaDemo/target/classes/_myPersistenceUnit logout successful

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();
EntityManager is used to interact with the persistence context. It provides all the methods to perform CRUD operations.

How to connect to the database using DBVisualizer and see the data of Employee table.

Install DBVisualizer (Download it from https://www.dbvis.com).


Open DBVisualizer.


Right click on Connections -> Create Database Connection.



Click on the button ‘Use Wizard’.



Give some name to the connection, for example, I had given jpaDemo. Click on Next button.



Select ‘JavaDB/Derby Server from the drop down. Click on Next button.



Update server, port, userId and password details. Give the database name as demoDatabase.

Click on ‘Ping Server’ button to validate the settings.

Click on Finish button.



Navigate to JpaDemo -> APP -> TABLE -> EMPLOYEE.

Now you can able to see the table EMPLOYEE and the data in it.

That’s it. I hope you enjoyed the basics…lets continue to get more knowledge on JPA.

References

Previous                                                    Next                                                    Home

No comments:

Post a Comment