CRUD using JPA on Hibernate, MySQL & Maven
This tutorial explains how to perform a simple CRUD using JPA Annotations on Hibernate, Maven and MySQL as Database.
Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications.
Lets see how to perform a CRUD Operation i.e. is Create, Read, Update & Delete using JPA on Hibernate, Maven and MySQL.
1. Project Setup
Lets create a simple Maven project with the below pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<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.heapcode.jpa</groupId> <artifactId>jpa-basic</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>jpa-basic</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.10.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.10.Final</version> </dependency> </dependencies> </project> |
In the above pom.xml we added dependencies for Hibernate 3.6.10, MySQL Connector 5.1.25, javassist and sl4j for logging.
2. Database Table Creation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
CREATE TABLE `EMPLOYEE` ( `EMPLOYEE_ID_PK` int(10) unsigned NOT NULL AUTO_INCREMENT, `FIRST_NAME` varchar(45) NOT NULL, `LAST_NAME` varchar(45) DEFAULT NULL, `EMAIL` varchar(45) NOT NULL, `PHONE_NO` int(11) NOT NULL, `CREATED_BY` int(10) unsigned NOT NULL, `CREATED_DATE` datetime NOT NULL, `MODIFIED_BY` int(10) unsigned NOT NULL, `MODIFIED_DATE` datetime NOT NULL, PRIMARY KEY (`EMPLOYEE_ID_PK`), UNIQUE KEY `EMAIL_UNIQUE` (`EMAIL`), UNIQUE KEY `EMPLOYEE_ID_PK_UNIQUE` (`EMPLOYEE_ID_PK`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1$$ |
The above script creates a table EMPLOYEE which looks as below
3. JPA Entity Class
Lets us create a JPA Entity Class Employee.java which is basically a Object Map of the above EMPLOYEE Table and it also contains the mapping specified using annotations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
package com.heapcode.jpa.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; /** * @author Manjunath Sampath * */ @Entity @Table(name = "EMPLOYEE", catalog = "heapcode", uniqueConstraints = { @UniqueConstraint(columnNames = "EMAIL") }) public class Employee implements Serializable { private static final long serialVersionUID = -6213555350782474664L; public Employee(){ } private int employeeIdPk; private String firstName; private String lastName; private String email; private Integer phoneNo; private int createdBy; private Date createdDate; private int modifiedBy; private Date modifiedDate; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "EMPLOYEE_ID_PK", unique = true, nullable = false) public int getEmployeeIdPk() { return employeeIdPk; } public void setEmployeeIdPk(int employeeIdPk) { this.employeeIdPk = employeeIdPk; } @Column(name = "FIRST_NAME", nullable = false, length = 45) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "LAST_NAME", length = 45) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name = "EMAIL",unique=true ,nullable = false, length = 45) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(name = "PHONE_NO", nullable = false) public Integer getPhoneNo() { return phoneNo; } public void setPhoneNo(Integer phoneNo) { this.phoneNo = phoneNo; } @Column(name = "CREATED_BY", nullable = false) public int getCreatedBy() { return createdBy; } public void setCreatedBy(int createdBy) { this.createdBy = createdBy; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "CREATED_DATE", nullable = false) public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } @Column(name = "MODIFIED_BY", nullable = false) public int getModifiedBy() { return modifiedBy; } public void setModifiedBy(int modifiedBy) { this.modifiedBy = modifiedBy; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "MODIFIED_DATE", nullable = false) public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } } |
4. Configuring Hibernate
Now let us create the JPA Configuration file persistence.xml. This is the master JPA Configuration File wherein we specify the Database URL, Credentials and specify the various mapping files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<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="HEAPCODE" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>com.heapcode.jpa.entity.Employee</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/> <property name="hibernate.configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" /> <property name="hibernate.bytecode.use_reflection_optimizer" value="true"/> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <property name="hibernate.connection.password" value="heapcode" /> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/heapcode" /> <property name="hibernate.connection.username" value="heapcode" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.max_fetch_depth" value="3"/> </properties> </persistence-unit> </persistence> |
6. Project Structure
The project after the above configuration would look like
7. CRUD Operation
1. CREATE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.heapcode.jpa.entity.Employee; public class JPAMain { /** * @param args */ public static void main(String[] args) { JPAMain jpaMain = new JPAMain(); jpaMain.create(); } private void create() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("HEAPCODE"); EntityManager em = emf.createEntityManager(); Employee employee = new Employee(); employee.setFirstName("John"); employee.setLastName("Trodd"); employee.setPhoneNo(12345); employee.setCreatedBy(0); employee.setModifiedBy(0); employee.setCreatedDate(new Date()); employee.setModifiedDate(new Date()); EntityTransaction tx = null; try{ tx = em.getTransaction(); tx.begin(); em.persist(employee); tx.commit(); }catch(RuntimeException re){ tx.rollback(); re.printStackTrace(); } em.close(); emf.close(); } } |
2. READ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.heapcode.jpa.main; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.heapcode.jpa.entity.Employee; public class JPAMain { /** * @param args */ public static void main(String[] args) { JPAMain jpaMain = new JPAMain(); jpaMain.read(); } private void read(){ EntityManagerFactory emf = Persistence.createEntityManagerFactory("HEAPCODE"); EntityManager em = emf.createEntityManager(); Employee employee = (Employee) em.find(Employee.class, 5); System.out.println(employee.getFirstName()); System.out.println(employee.getLastName()); System.out.println(employee.getEmail()); em.close(); emf.close(); } } |
3. UPDATE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.heapcode.jpa.main; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.heapcode.jpa.entity.Employee; public class JPAMain { /** * @param args */ public static void main(String[] args) { JPAMain jpaMain = new JPAMain(); jpaMain.update(); } private void update(){ EntityManagerFactory emf = Persistence.createEntityManagerFactory("HEAPCODE"); EntityManager em = emf.createEntityManager(); Employee employee = (Employee) em.find(Employee.class, 5); employee.setPhoneNo(23456); EntityTransaction tx = null; try{ tx = em.getTransaction(); tx.begin(); em.merge(employee); tx.commit(); }catch(RuntimeException re){ tx.rollback(); re.printStackTrace(); } em.close(); emf.close(); } } |
4. DELETE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.heapcode.jpa.main; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.heapcode.jpa.entity.Employee; public class JPAMain { /** * @param args */ public static void main(String[] args) { JPAMain jpaMain = new JPAMain(); jpaMain.delete(); } private void delete(){ EntityManagerFactory emf = Persistence.createEntityManagerFactory("HEAPCODE"); EntityManager em = emf.createEntityManager(); Employee employee = (Employee) em.find(Employee.class, 5); EntityTransaction tx = null; try{ tx = em.getTransaction(); tx.begin(); em.remove(employee); tx.commit(); }catch(RuntimeException re){ tx.rollback(); re.printStackTrace(); } em.close(); emf.close(); } } |
Download JPA MySQL Maven Example Project
I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.