DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Handling Embedded Data in NoSQL With Java
  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3
  • Finally, an ORM That Matches Modern Architectural Patterns!

Trending

  • A Guide to Container Runtimes
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Unlocking AI Coding Assistants Part 3: Generating Diagrams, Open API Specs, And Test Data
  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  1. DZone
  2. Data Engineering
  3. Databases
  4. JPA Tutorial: Setting Up JPA in a Java SE Environment

JPA Tutorial: Setting Up JPA in a Java SE Environment

There are many reasons to learn an ORM tool like JPA, but it's not a magic bullet that will solve all your problems.

By 
MD Sayem Ahmed user avatar
MD Sayem Ahmed
·
Aug. 18, 14 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
145.3K Views

Join the DZone community and get the full member experience.

Join For Free

jpa stands for java persistence api, which basically is a specification that describes a way to persist data into a persistent storage, usually a database. we can think of it as something similar to orm tools like hibernate , except that it is an official part of the java ee specification (and it’s also supported on java se).

there are many reasons to learn an orm tool like jpa. i will not go into the details of this because there are already many posts on the web which perfectly answer this question, like this one , or this one . however, we should also keep in mind that this is not a single magic bullet which will solve our every problem.

when i first started out with jpa, i had real difficulties to set it up because most of the articles on the web are written for java ee environment only, whereas i was trying to use it in a java se environment. i hope that this article will be helpful for those who wish to do the same in the future.

in this example we will use maven to set up our required dependencies. since jpa is only a specification, we will also need an implementation. there are many good implementations of jpa available freely (like eclipselink, hibernate etc.). for this article i have chosen to use hibernate. as for the database, i will use mysql.

let us first create a simple maven project. i have created mine using the quick start archetype from the command line. if you do not know how to do that, you can follow this tutorial .

ok, so let us get the dependencies for the jpa next. include the following lines in your pom.xml -

<dependency>
  <groupid>javax.persistence</groupid>
  <artifactid>persistence-api</artifactid>
  <version>1.0.2</version>
</dependency>
<dependency>
  <groupid>org.hibernate</groupid>
  <artifactid>hibernate-entitymanager</artifactid>
  <version>4.3.6.final</version>
  <exclusions>
    <exclusion>
      <groupid>org.hibernate.javax.persistence</groupid>
      <artifactid>hibernate-jpa-2.1-api</artifactid>
    </exclusion>
  </exclusions>
</dependency>

the first dependency specifies the standard jpa interface, and the second one specifies the implementation. including jpa dependencies this way is desirable because it gives us the freedom to switch vendor-specific implementation in the future without much problem ( see details here ). however we will not be able to use the latest version of the api this way because the api version 1.0.2 is the last version that is released as an independent jar. at the time of writing this article, the latest version of the jpa specification is 2.1 which is not available independently (there are lots of requests for it though). if we want to use that one now then our only options are to choose from either a vendor-specific jar or use an application server which provides the api along with its implementation. i have decided to use the api specification provided by hibernate. in that case including only the following dependency will suffice -

<dependency>
  <groupid>org.hibernate</groupid>
  <artifactid>hibernate-entitymanager</artifactid>
  <version>4.3.6.final</version>
</dependency>

next step is to include the dependency for mysql. include the following lines in your pom.xml -

<dependency>
  <groupid>mysql</groupid>
  <artifactid>mysql-connector-java</artifactid>
  <version>5.1.31</version>
</dependency>

after including the rest of the dependencies (i.e., junit, hamcrest etc.) the full pom.xml looks like below -

<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>com.keertimaan.javasamples</groupid>
  <artifactid>jpa-example</artifactid>
  <version>0.0.1-snapshot</version>
  <packaging>jar</packaging>

  <name>jpa-example</name>
  <url>http://sayemdb.wordpress.com</url>

  <properties>
    <java.version>1.8</java.version>
    <hibernate.version>4.3.6.final</hibernate.version>
    <project.build.sourceencoding>utf-8</project.build.sourceencoding>
  </properties>

  <dependencies>
    <!-- jpa -->
    <dependency>
      <groupid>org.hibernate</groupid>
      <artifactid>hibernate-entitymanager</artifactid>
      <version>${hibernate.version}</version>
    </dependency>

    <!-- for connection pooling -->
    <dependency>
      <groupid>org.hibernate</groupid>
      <artifactid>hibernate-c3p0</artifactid>
      <version>${hibernate.version}</version>
    </dependency>

    <!-- database -->
    <dependency>
      <groupid>mysql</groupid>
      <artifactid>mysql-connector-java</artifactid>
      <version>5.1.31</version>
    </dependency>

    <!-- test -->
    <dependency>
      <groupid>junit</groupid>
      <artifactid>junit</artifactid>
      <version>4.11</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupid>org.hamcrest</groupid>
          <artifactid>hamcrest-core</artifactid>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupid>org.hamcrest</groupid>
      <artifactid>hamcrest-all</artifactid>
      <version>1.3</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupid>org.apache.maven.plugins</groupid>
        <artifactid>maven-compiler-plugin</artifactid>
        <version>2.5.1</version>
        <configuration>
          <source>${java.version}</source>
          <target>${java.version}</target>
          <compilerargument>-xlint:all</compilerargument>
          <showwarnings>true</showwarnings>
          <showdeprecation>true</showdeprecation>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

now it’s time to configure our database. i will use the following schema in all of my future jpa examples which i found from this excellent online book -

database schema

database schema

create an equivalent database following the above schema in your local mysql installation.

our next step is to create the persistence.xml file which will contain our database specific information for jpa to use. by default jpa expects this file to be in the class path under the meta-inf folder. for our maven project, i have created this file under project_root/src/main/resources/meta-inf folder -

<persistence 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"

  version="2.1">

  <persistence-unit name="jpa-example" transaction-type="resource_local">
  <provider>org.hibernate.jpa.hibernatepersistenceprovider</provider>

  <properties>
    <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/jpa_example" />
    <property name="javax.persistence.jdbc.user" value="root" />
    <property name="javax.persistence.jdbc.password" value="my_root_password" />
    <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.driver" />

    <property name="hibernate.show_sql" value="true" />
    <property name="hibernate.format_sql" value="true" />
    <property name="hibernate.dialect" value="org.hibernate.dialect.mysql5innodbdialect" />
    <property name="hibernate.hbm2ddl.auto" value="validate" />

    <!-- configuring connection pool -->
    <property name="hibernate.c3p0.min_size" value="5" />
    <property name="hibernate.c3p0.max_size" value="20" />
    <property name="hibernate.c3p0.timeout" value="500" />
    <property name="hibernate.c3p0.max_statements" value="50" />
    <property name="hibernate.c3p0.idle_test_period" value="2000" />
    </properties>
  </persistence-unit>
</persistence>

the above file requires some explanation if you are an absolute begineer in jpa. in my next article i will try to explain it as much as possible, but for running this example you will only need to change the first three property values to match your environment (namely the database name, username and password). also keep a note of the value of the name attribute of the persistence-unit element. this value will be used to instantiate our entitymanagerfactory instance later in the code.

ok, let us now create an entity to test our configuration. create a class called address with the following contents -

import javax.persistence.entity;
import javax.persistence.generatedvalue;
import javax.persistence.id;
import javax.persistence.table;

@entity
@table(name = "address")
public class address {
  @id
  @generatedvalue
  private integer id;

  private string street;
  private string city;
  private string province;
  private string country;
  private string postcode;

  /**
   * @return the id
   */
  public integer getid() {
    return id;
  }

  /**
   * @param id the id to set
   */
  public address setid(integer id) {
    this.id = id;
    return this;
  }

  /**
   * @return the street
   */
  public string getstreet() {
    return street;
  }

  /**
   * @param street the street to set
   */
  public address setstreet(string street) {
    this.street = street;
    return this;
  }

  /**
   * @return the city
   */
  public string getcity() {
    return city;
  }

  /**
   * @param city the city to set
   */
  public address setcity(string city) {
    this.city = city;
    return this;
  }

  /**
   * @return the province
   */
  public string getprovince() {
    return province;
  }

  /**
   * @param province the province to set
   */
  public address setprovince(string province) {
    this.province = province;
    return this;
  }

  /**
   * @return the country
   */
  public string getcountry() {
    return country;
  }

  /**
   * @param country the country to set
   */
  public address setcountry(string country) {
    this.country = country;
    return this;
  }

  /**
   * @return the postcode
   */
  public string getpostcode() {
    return postcode;
  }

  /**
   * @param postcode the postcode to set
   */
  public address setpostcode(string postcode) {
    this.postcode = postcode;
    return this;
  }
}

this class has been properly mapped to the address table and its instances are fully ready to be persisted in the database. now let us create a helper class called persistencemanager with the following contents -

import javax.persistence.entitymanager;
import javax.persistence.entitymanagerfactory;
import javax.persistence.persistence;

public enum persistencemanager {
  instance;

  private entitymanagerfactory emfactory;

  private persistencemanager() {
    // "jpa-example" was the value of the name attribute of the
    // persistence-unit element.
    emfactory = persistence.createentitymanagerfactory("jpa-example");
  }

  public entitymanager getentitymanager() {
    return emfactory.createentitymanager();
  }

  public void close() {
    emfactory.close();
  }
}

now let us write some sample persistence code in our main method to test everything out -

import javax.persistence.entitymanager;

public class main {
  public static void main(string[] args) {
    address address = new address();
    address.setcity("dhaka")
        .setcountry("bangladesh")
        .setpostcode("1000")
        .setstreet("poribagh");

    entitymanager em = persistencemanager.instance.getentitymanager();
    em.gettransaction()
        .begin();
    em.persist(address);
    em.gettransaction()
        .commit();

    em.close();
    persistencemanager.instance.close();
  }
}

if you check your database, you will see that a new record has been inserted in your address table.

this article explains how to set up jpa without using any other frameworks like spring. however, it is a very good idea to use spring to set up jpa because in that case we do not need to worry about managing entity managers, transactions etc. besides setting up jpa, spring is also very good for many other purposes too.

that’s it for today. in the next article, i will try to explain the persistence.xml file and the corresponding configuration values as much as possible. stay tuned!

the full code can be found at github .

Database Java (programming language)

Published at DZone with permission of MD Sayem Ahmed, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Handling Embedded Data in NoSQL With Java
  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3
  • Finally, an ORM That Matches Modern Architectural Patterns!

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!