- Java Development Kit (JDK 1.8 or above)
- MySQL, includes MySQL database server, MySQL Command Line Client, and MySQL Workbench tool (MySQL 5.5 or above)
- Eclipse IDE (Neon or later)
Here are the steps you will follow in this tutorial:1. Overview of JPA and Hibernate
3. Setup Java Maven Project in Eclipse
5. Create JPA Configuration File (persistence.xml)
6. Understand EntityManager and EntityManagerFactory
create database usersdb;Then create a table name users with 4 columns: user_id, fullname, email and password, using the following script:
CREATE TABLE `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `fullname` varchar(45) NOT NULL, `email` varchar(45) NOT NULL, `password` varchar(45) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1Using desc users command in MySQL Command Line Client, the structure of the table looks like this:Note that the column user_id is the table’s primary key and it is auto-increment.
- Group Id: net.codejava.hibernate
- Artifact Id: HibernateJPABeginner
Leave other things as they are and click Finish. In the Project Explorer view, you see the project gets created with the following structure:<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.12.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.8-dmr</version> </dependency> </dependencies>You see, here we add two dependencies for the project: hibernate-core and mysql-connector-java. Maven automatically downloads the required JAR files which are shown under the Maven Dependencies node in the project:You see, we just specify the dependency hibernate-core, but Maven can analyze and download all the dependencies of hibernate-core as well. That’s really helpful, right?Create a new Java package name net.codejava.hibernate under the src/main/java folder. We’ll put our Java classes in this package.
package net.codejava.hibernate; /** * User.java * Copyright by CodeJava.net */ public class User { private Integer id; private String fullname; private String email; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }You see, this is just a POJO (Plain Old Java Object) class with some instance fields and its getter and setter methods. Now, let’s use some annotations provided by JPA to map this model class to the users table in the database. @EntityThis annotation indicates that the class is mapped to a database table. By default, the ORM framework understands that the class name is as same as the table name. The @Entity annotation must be placed before the class definition:
@Entity public class User { … }@TableThis annotation is used if the class name is different than the database table name, and it is must placed before the class definition. Since the class name is User and the table name is Users, we have to use this annotation:
@Entity @Table(name = "USERS") public class User {@ColumnThis annotation is used to map an instance field of the class to a column in the database table, and it is must placed before the getter method of the field. By default, Hibernate can implicitly infer the mapping based on field name and field type of the class. But if the field name and the corresponding column name are different, we have to use this annotation explicitly. ThisIn our model class, the field name id is different than the column user_id, so we have to use the @Column annotation as follows:
@Column(name = "USER_ID") public Integer getId() { return id; }The other fields (fullname, email and password) have identical names as the corresponding columns in the table so we don’t have to annotate those fields. @IdThis annotation specifies that a field is mapped to a primary key column in the table. Since the column user_id is a primary key, we have to use this annotation as follows:
@Column(name = "USER_ID") @Id public Integer getId() { return id; }@GeneratedValueIf the values of the primary column are auto-increment, we need to use this annotation to tell Hibernate knows, along with one of the following strategy types: AUTO, IDENTITY, SEQUENCE, and TABLE. In our case, we use the strategy IDENTITY which specifies that the generated values are unique at table level, whereas the strategy AUTO implies that the generated values are unique at database level.Therefore, the getter method of the field id is annotated as follows:
@Column(name = "USER_ID") @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getId() { return id; }Finally, we have the model class User is annotated as follows:
package net.codejava.hibernate; import javax.persistence.*; @Entity @Table(name = "USERS") public class User { private Integer id; private String fullname; private String email; private String password; @Column(name = "USER_ID") @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getId() { return id; } // other setters and getters are not shown for brevity }
Java Servlet, JSP and Hibernate: Build eCommerce Website
Code Functional Bookshop Website with Java Servlet and Hibernate framework. Full-stack Development. Job-ready Skills.
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" 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"> <persistence-unit name="UsersDB"> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/usersdb" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="P@ssw0rd" /> <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" /> </properties> </persistence-unit> </persistence>The root element <persistence> specifies the version of JPA to be used, and as you can see, we use JPA version 2.1.The element <persistence-unit> specifies a unit of persistence with a name. The name (UsersDB) will be looked up by Java code.Then we specify several properties for database connection information:
- javax.persistence.jdbc.url: specifies the JDBC URL points to the database.
- javax.persistence.jdbc.user: specifies the username of the account having privilege to access to the database.
- javax.persistence.jdbc.password: specifies the password of the user.
- javax.persistence.jdbc.driver: specifies the class name of the JDBC driver to be used. Here we use MySQL Connector Java so the name is com.mysql.jdbc.Driver.
- hibernate.show_sql: tells Hibernate to show SQL statements in standard output.
- hibernate.format_sql: tells Hibernate to format the SQL statements.
So you may need to change the values for url, user, and password accordingly.- Create an EntityManagerFactory from a persistence unit
- Create an EntityManager from the EntityManagerFactory
- Begin a transaction
- Manage entity instances (create, update, remove, find, query, etc)
- Commit the transaction
- Close the EntityManager and EntityManagerFactory
Let’s see the code details below.EntityManagerFactory factory = Persistence.createEntityManagerFactory("UsersDB"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin();And write the following code to saves a new User object to the database:
User newUser = new User(); newUser.setEmail("billjoy@gmail.com"); newUser.setFullname("bill Joy"); newUser.setPassword("billi"); entityManager.persist(newUser);As you can see, we call the persist(Object) method of the EntityManager class to save the User object to the underlying database.And finally commit the transaction and close the EntityManager and EntityManagerFactory:
entityManager.getTransaction().commit(); entityManager.close(); factory.close();So the complete program should look like this:
package net.codejava.hibernate; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * UserDAOTest.java * Copyright by CodeJava.net */ public class UserDAOTest { public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("UsersDB"); EntityManager entityManager = factory.createEntityManager(); entityManager.getTransaction().begin(); User newUser = new User(); newUser.setEmail("billjoy@gmail.com"); newUser.setFullname("bill Joy"); newUser.setPassword("billi"); entityManager.persist(newUser); entityManager.getTransaction().commit(); entityManager.close(); factory.close(); } }Run this program, and you should see the following output in the Console view: You see, Hibernate prints the SQL statement which is nicely formatted. That means the program has been executed successfully. You can check the result by typing the command “select * from users” in MySQL Command Line Client tool:You see, a new row created and you don’t have to write any SQL statement, right? That’s the power of using Hibernate/JPA for database programming.Let’s see how to perform other operations.
User existingUser = new User(); existingUser.setId(1); existingUser.setEmail("bill.joy@gmail.com"); existingUser.setFullname("Bill Joy"); existingUser.setPassword("billionaire"); entityManager.merge(existingUser);As you can see, we need to specify the ID of the object and use the merge(Object) method of the EntityManager class.
Integer primaryKey = 1; User user = entityManager.find(User.class, primaryKey); System.out.println(user.getEmail()); System.out.println(user.getFullname()); System.out.println(user.getPassword());This code finds the user with ID = 1 in the database.
String sql = "SELECT u from User u where u.email = 'bill.joy@gmail.com'"; Query query = entityManager.createQuery(sql); User user = (User) query.getSingleResult(); System.out.println(user.getEmail()); System.out.println(user.getFullname()); System.out.println(user.getPassword());Note that the query looks similar to traditional SQL syntax but it is not. The difference is JPQL operates against entity instances (Java objects) rather than tables in database.
Integer primaryKey = 1; User reference = entityManager.getReference(User.class, primaryKey); entityManager.remove(reference);As you can see, this code removes the User object with ID = 1 from the database, first by looking up a reference based on the class type (User.class) and primary key value (1), then remove the reference.That’s how to get started with Hibernate/JPA with Eclipse and MySQL. We hope this tutorial is helpful for you. Happy coding!I recommend you take this course to Learn Java Servlet, JSP, Hibernate framework to build an eCommerce Website (with PayPal and credit card payment).