This article is a continuation of Creating a Database Using MySQL Command-Line Client.
This article is a continuation of the previous article in which we made a database from scratch using MySQL command-line client. For a head start check it out here: Creating a Database Using MYSQL Command-Line Client.
In this article, we will learn how to create Java model classes that map to the tables in the database using Hibernate and JPA application programming interfaces. We will discuss Java persistence API and Hibernate framework.
Then we will see how to create a model class manually using JPA annotations.
Let’s start with some basic definitions of our core concepts.
JPA is a Java API specification for relational data management in an application using Java SE and Java EE.
version used: JPA 2.1
API package: javax.persistence
Java Persistence Query Language is an OOQL that is used to make queries against entities stored in a relational database. Its syntax is similar to SQL, but it operates against Java objects instead of directly with the database table. JPA is a specification and its implementation includes Hibernate, EclipseLink and OpenJPA.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import javax.persistence.*;
@Entity
public class Book {
private Interger bookId;
private String title;
@Id
@Column(name = "book_id")
public Integer getBookId() {
return this.bookId;
}
@Column(name = "title")
public Integer getTitle() {
return this.title;
}
}
The book class is mapped to the book table in the database using the annotation @Entity. The other two fields bookId and title are mapped to book_id and title respectively using the @Column annotation. The @Id indicates that this column is the primary key.
Example Query: SELECT bo FROM BookOrder ORDER BY bo.amount
It looks very similar to SQL but we can see the object-oriented syntax here: b.title
Hibernate is a popular object relational mapping (ORM) framework that simplifies database programming for developers. Hibernate restructures itself to become an implementation or provider of JPA.
That means we can use Hibernate independently or use it as an implementation of JPA.
Hibernate framework consists of several components, the first of which is Hibernate ORM. Hibernate ORM is the core of the framework on which other components depend. We use it for mapping Java model classes to tables in relational databases.
Hibernate Search is a full-text search component for the domain model.
Hibernate Validator is the component for making constraints for the domain model. Hibernate OGM is the domain model persistence component for NoSQL databases. Hibernate tools is a set of plugins for Eclipse IDE facilitating Hibernate development within Eclipse. It provides a mapping editor, console, and reverse engineering. In this article, we use only Hibernate ORM and Hibernate Tools.
Before we create our first model class, let’s review the tables in the database BookstoreDB, which we created in our previous article. Below you see the entity-relationship diagram that describes the tables and the relations among them.
We are going to manually create a model class that maps to the table users. In our next article, we will be generating other model classes using Hibernate reverse engineering tool.
Before we start coding our class we need to create, set up, and configure a Java project in Eclipse IDE for developing the Book Store website for our client. We are to create a Java dynamic web project which enables the development of web applications based on Java servlets and Java server pages. We can talk about the whole process in some other article in the future but for now, you can follow some docs and create a Java dynamic web project whose file structure looks like the below.
Our project name is BookStoreWebsite
Steps:
Create a POJO class: Users.java
As seen in the entity-relationship diagram we have four fields: userId, email, fullName, and password. Now we can use getters and setters using shortcuts just right click > source > generate getters and setters.
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
public class Users {
private Integer userId;
private String email;
private String fullName;
private String password;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Now, as we have created a POJO class we can use JPA annotations to tell the ORM framework that this class is mapped to a table in the database.
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
@Entity
public class Users {
private Integer userId;
private String email;
private String fullName;
private String password;
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "full_name")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@Entity: Annotation to specify that this class is mapped to the table in the database with the same name.
@Column(name = “full_name”): Specifies the actual column name of the field in the database. It is only used when the column name differs from that of the class and that too before the getter method of a field.
@Id: Defines the primary key of the table.
@GeneratedValue(strategy = GenerationType.IDENTITY): Used before the getter method of the field that mapped to the primary key column in the database.
Create JPA config File: persistence.xml
Now we need to create a configuration file to initially specify database connection information so Hibernate can use it to connect to the database. In JPA this configuration should be named persistence.xml and is put under the META_INF folder in the source folder of the project. Now go ahead and create this folder and create an XML file, like below.
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
<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> `` `xml Persistence is the root element of the XML file. To use the correct version of the persistence element you should Google ‘JPA XML schema’. I used one from Oracle, and since we are using 2.1, click on the persistence_2_1.xsd and get the part similar to above. ` `` xml < persistence - unit name = "BookStoreWebsite" > <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/bookstoredb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="MySQL@1234"/> <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.c3p0.min_size" value="5"/> <property name="hibernate.c3p0.max_size" value="10"/> <property name="hibernate.c3p0.timeout" value="120"/> <property name="hibernate.c3p0.max_statements" value="50"/> <property name="hibernate.c3p0.idle_test_period" value="3000"/> </properties> < /persistence-unit> < /persistence>
Above are the contents of the XML file you need to configure. Here we have specified the persistence unit with the name BookStoreWebsite (name of our application).
We need to specify various properties:
The first property specifies the JDBC URL so its name is javax.persistence.jdbc.url and the value is a JDBC URL that points to our BookstoreDB. The value jdbc:mysql:// localhost is the hostname of MySQL database server, the port number is 3306 and the database name is bookstoredb.
The second property is the database user name, in our case it is root.
The third property is the password of the database user.
The last property is the driver class name of MySQL JDBC.
In this article we learned how to create Java model classes that map to the tables in a database using Hibernate and JPA application programming interfaces. We also learned Java persistence API, Hibernate framework, and about some of JPA annotations.