JPA Example using Maven and Hibernate as JPA Provider
In this tutorial, we will create a simple JPA example using Maven, Hibernate 4 JPA Provider and MySQL.
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 used Hibernate as JPA provider. I used mysql as a database and eclipse as IDE.
Tools used :
- Maven 3.0.5
- Hibernate 4
- Eclipse
- JDK 7
- mySql 5.1
In this tutorial, we will create a simple JPA example using Maven, Hibernate 4 JPA Provider and MySQL.
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 used Hibernate as JPA provider. I used mysql as a database and eclipse as IDE.
Tools used :
- Maven 3.0.5
- Hibernate 4
- Eclipse
- JDK 7
- mySql 5.1
Table Creation
Create table "EMP_DB" in mySql database.
create table EMP_DB ( id INT NOT NULL, fistName VARCHAR(20) default NULL, lastName VARCHAR(20) default NULL, dept VARCHAR(20) default NULL, PRIMARY KEY (id) );
Create java Project using Maven
In the command prompt execute the following command to generate Maven compatible Java project named as 'JPAMavenExample'.
Note:- I will highly recommend to go through How To Create A Java Project With Maven tutorial if you have no idea about how to create java project using maven.
mvn archetype:generate -DgroupId=com.javawebtutor -DartifactId=JPAMavenExample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This command creates a new Java project under the name 'JPAMavenExample', along with its entire directory structure.
Convert to eclipse project
To convert Maven project to support Eclipse IDE, in terminal, navigate to 'JPAMavenExample' project, and issue mvn eclipse:eclipse command .
Import converted project into Eclipse IDE
In Eclipse IDE, Choose File –> Import –> General -> Existing Projects into Workspace –>Choose your project folder location. Done
Create a resources folder
Create a 'resources' folder under "src/main" directory and add this folder to the class path of the project.You can add the folder in the classpath by following steps.
Right click on the project and navigate to -> Build Path -> Configure Build Path, click on the Source tab and then click on Add Folder button as shown below.
In the next screen check the checkbox resources and click on OK button as shown below.
Directory Structure of Project
Add jpa and hibernate dependency in pom.xml
Once your Maven base project has been created using Eclipse, Define the below hibernate,mysql and other dependencies in 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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javawebtutor</groupId> <artifactId>JPAMavenExample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>JPAMavenExample</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.2.8.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.27</version> </dependency> </dependencies> </project>
Issue the “mvn eclipse:eclipse“, Maven will download all Hibernate, JPA and MySQL libraries automatically and put into Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse “.classpath” for dependency purpose.
Creating persistence.xml file
Create META-INF folder inside resources directory.Create persistence.xml inside META-INF folder. This file specifies JPA provider and it’s properties.Add following code in persistence.xml file.
persistence.xml<?xml version="1.0" encoding="UTF-8"?> <persistence 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" version="2.0"> <persistence-unit name="EmployeePU"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.url" value="jdbc:mysql://localhost/jpadb" /> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="mukesh" /> <property name="hibernate.archive.autodetection" value="class" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence>
Create Entity class
Craete a java class 'Employee' in the package com.javawebtutor and add following code in this class.
Employee.java
package com.javawebtutor; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "EMP_DB") public class Employee { @Id @Column(name = "id") private int id; @Column(name = "fistName") private String firstName; @Column(name = "lastName") private String lastName; @Column(name = "dept") private String dept; public Employee() { } public Employee(int id, String firstName, String lastName, String dept) { this.setId(id); this.setFirstName(firstName); this.setLastName(lastName); this.setDept(dept); } 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; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } }
Test Class
Create Test class named 'JpaTest' to insert some sample data in the EMP_DB table.
package com.javawebtutor; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class JpaTest { private static EntityManager em; public static void main(String[] args) { EntityManagerFactory emf = Persistence .createEntityManagerFactory("EmployeePU"); em = emf.createEntityManager(); createEmployee(1, "Ravi", "Raj", "Textile"); createEmployee(2, "Amit", "Raj", "IT"); createEmployee(3, "Nitish", "Kumar", "Marketing"); } private static void createEmployee(int id, String firstName, String lastName, String dept) { em.getTransaction().begin(); Employee emp = new Employee(id, firstName, lastName, dept); em.persist(emp); em.getTransaction().commit(); } }
Output
Run the JpaTest class you will see following output in console.
Hibernate: Hibernate: insert into EMP_DB (dept, fistName, lastName, id) values (?, ?, ?, ?) Hibernate: insert into EMP_DB (dept, fistName, lastName, id) values (?, ?, ?, ?) Hibernate: insert into EMP_DB (dept, fistName, lastName, id) values (?, ?, ?, ?)
Now Check the EMP_DB Table you can see data is stored in table
mysql> select * from emp_db; +----+----------+----------+-----------+ | id | fistName | lastName | dept | +----+----------+----------+-----------+ | 1 | Ravi | Raj | Textile | | 2 | Amit | Raj | IT | | 3 | Nitish | Kumar | Marketing | +----+----------+----------+-----------+ 3 rows in set (0.00 sec)
You can download the source code of the example by clicking on the Download link below.
Source : Download |