In this quick tutorial, we discuss how to get started working with JPA + Hibernate + Maven application using Mysql DB.
Project Structure
- Import downloaded project into eclipse. If you are new to maven follow Import maven project into eclipse.
- Imported project structure looks like below screen.
pom.xml (Project Object Model):
- It is an XML file that contains information about the project and configuration details used by Maven to build the project.
- We will define required jars or wars or libraries as dependencies. Below is the pom.xml looks like.
- All the required JPA and Hibernate dependencies will be defined here.
<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.javabydeveloper</groupId> <artifactId>JPA-Helloworld</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>JPA-Helloworls</name> <url>https://javabydeveloper.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <!-- Hibernate 5.2.6 Final --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.21.Final</version> </dependency> <!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.4.21.Final</version> </dependency> --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
Update maven dependencies after project imported :
- Right click on project –> select “maven” –> select “Update Project”. Follow below screen.
- Select “Force Update…” check box –> click “OK”. This will update all dependencies to the project.
Run SQL script that provided in sample application:
- Every download of sample application includes sql file also.
- Copy provided sql script and execute using MySql workbench. Follow below screen.
- Paste sql code in the editor –> select part of script or whole script that you want to execute –> issue command CTRL+SHIFT+ENTER (in windows, CMD+SHIFT+ENTER in Mac).
Persistence.xml :
- Every sample application includes persistence.xml inside META-INF directory.
- JPA uses the persistence.xml file to create the connection and setup the required environment. Provides information which is necessary for making database connections.
- Persistence units are defined by the persistence.xml configuration file.
- A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application.
<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="jbd-pu"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_jbd?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="password" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" /> </properties> </persistence-unit> </persistence>
Student Entity:
@Table(name="Student") @Entity(name = "Stu") public class Student { @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "native") @GenericGenerator(name = "native", strategy = "native") @Column(name = "ID") private Long studentId; @Column(name = "FNAME") private String firstName; @Column(name = "LNAME") private String lastName; @Column(name = "CONTACT_NO") private String contactNo; // setters, getters and toString() }
App.java – main class to test the code :
- All the entities are available under “domain” source directory.
- You will find App.java, use that class to run the test.
public class App { public static void main(String[] args) { EntityManagerFactory emf = null; EntityManager entityManager = null; EntityTransaction transaction = null; try { emf = Persistence.createEntityManagerFactory("jbd-pu"); entityManager = emf.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); Student student = new Student(); student.setFirstName("John"); student.setLastName("Bloch"); student.setContactNo("+1-408-575-1317"); entityManager.persist(student); transaction.commit(); Query q = entityManager.createQuery("select s from Stu s"); List<Student> resultList = q.getResultList(); System.out.println("num of sudents:" + resultList.size()); for (Student next : resultList) { System.out.println("next student: " + next); } } catch (Exception e) { System.out.println(e); transaction.rollback(); } finally { entityManager.close(); emf.close(); } } }
Source code download.