- November 24, 2020
- saptrxuy_learnit
- 0 Comments
- 1808 Views
- 0 Likes
- Hibernate, Java
Java Project with Hibernate and JPA
1 Introduction
2 Create a Java project and a package
3 Create a database and a table in Mysql
4 Add Dependencies
5 Create Student class
6 Create /resource/META-INF/persistence.xml file
7 Create Main Class
8 Create a method to a record to DB Table
9 Print list of Students
10 Update Student
11 Delete Student
12 Close the Entity Manager Factory
1.Introduction▲
This document describes how to create Java project with Hibernate and JPA.
1.1.Software Requirements:▲
Java JDK
Maven
Mysql
1.2.Dependencies Requirements:▲
Hibernate libraries
MySQL JDBC connector
1.3.What is Hibernate?▲
Hibernate is an Object/Relational Mapping solution for Java environments. The term Object/Relational Mapping refers to the technique of mapping data from an object model representation to a relational data model representation (and visa versa).
Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities.
1.4.What is JPA?▲
Java Persistence API (JPA) is a Java specification that provides certain functionality and standard to ORM tools. It provides a POJO persistence model for object-relational mapping. The javax.persistence package contains the JPA classes and interfaces. Java Persistence consists of four areas:
The Java Persistence API
The query language
The Java Persistence Criteria API
Object/relational mapping metadata
2.Create a Java project and a package▲
Create Java project xv-training-java-hibernate. Then create xv.training.java.hibernate package.
3.Create a database and a table in Mysql▲
CREATE DATABASE IF NOT EXISTS dbJavaHbJpa;
CREATE TABLE dbJavaHbJpa.student (
id INT NOT NULL ,
name VARCHAR(45) NOT NULL ,
age INT NOT NULL ,
PRIMARY KEY (id) );
4.Add Dependencies▲
4.1.Create a /lib folder▲
4.2.Hibernate▲
Download and extract the Hibernate libraries, from this link: Hibernate ORM.
Copy all the *.jar files from “hibernate-release-xxx/lib/required” folder and paste them into the “lib” folder of the project.
4.3.MySQL JDBC connector▲
Download and extract the MySQL JDBC connector, from this link: Download Connector/J
Copy the mysql-connector-java-xxx.jar file to “lib” folder of the project.
4.4.Add lib jars to the project classpath▲
- Select Project -> Properties -> Java Build Path – > Libraries -> Classpath
- Click Add Jars -> Select current project -> lib -> select all jars -> OK
- Apply and close
5.Create Student class▲
In package xv.training.java.hibernate, create Student class. Then add two members id and name. Generate getter setter and toString method. Add @Entity annotation to the Student class. Add @Id and @column annotation to the field.
5.1.javax.persistence.Entity ▲
An entity is a lightweight persistence domain object. An entity represents a table in a relational database, and each entity instance corresponds to a row in that table.
An entity class must follow these requirements.
- The class must be annotated with the javax.persistence.Entity annotation.
- The class must have a public or protected, no-argument constructor. The class may have other constructors.
- The class must not be declared final. No methods or persistent instance variables must be declared final.
- If an entity instance is passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface.
- Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.
- Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class’s methods. Clients must access the entity’s state through accessor or business methods.
5.2.javax.persistence.Id – JPA @Id annotation ▲
Specifies the primary key of an entity. The mapped column for the primary key of the entity is assumed to be the primary key of the primary table. If no Column annotation is specified, the primary key column name is assumed to be the name of the primary key property or field.
5.3.javax.persistence.Column – JPA @Column annotation▲
@Column annotation is used to specify the mapped column for a persistent property or field. If no Column annotation is specified, the default values apply.
5.4.Code▲
package xv.training.java.hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = “student”)
public class Student implements Serializable {
@Id
@Column(name = “id”, unique = true)
private int id;
@Column(name = “name”, nullable = false)
private String name;
@Column(name = “age”, nullable = false)
private int age;
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return “Student [id=” + id + “, name=” + name + “, age=” + age + “]”;
}
}
6.Create /resource/META-INF/persistence.xml file▲
6.1.What is persistence.xml file?▲
The persistence.xml file is a standard configuration file in JPA. It has to be included in the META-INF directory inside the JAR file that contains the entity beans. The persistence.xml file must define a persistence-unit with a unique name in the current scoped classloader. The provider attribute specifies the underlying implementation of the JPA EntityManager. This persistence.xml holds the configuration for connecting to database.
6.2.Create empty persistence.xml file▲
6.3.Add xml header▲
<?xml version=“1.0” encoding=“UTF-8”?>
6.4.Add header for persistence▲
<persistence version=“2.0”
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”>
</persistence>
6.5.Add persistence unit▲
<persistence-unit name=“mysqlWithHibernate” transaction-type=“RESOURCE_LOCAL”>
</persistence-unit>
6.5.1.Add Persistence provider▲
<!– Persistence provider –>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
6.5.2.Give reference of Entity classes▲
<!– Entity classes –>
<class>xv.training.java.hibernate.Student</class>
6.5.3.Add db details▲
<properties>
<!– The JDBC driver of your database –>
<property name=”javax.persistence.jdbc.driver” value=”com.mysql.jdbc.Driver” />
<!– The JDBC URL to the database instance –>
<property name=”javax.persistence.jdbc.url”
value=”jdbc:mysql://127.0.0.1:3306/dbjavahbjpa?serverTimezone=UTC” />
<!– The database username –>
<property name=”javax.persistence.jdbc.user” value=”root” />
<!– The database password –>
<property name=”javax.persistence.jdbc.password” value=”YOUR-MYSQL-DATABASE-PASSWORD” />
<property name=”hibernate.dialect” value=”org.hibernate.dialect.MySQLInnoDBDialect”/>
</properties>
7.Create Main Class▲
7.1.In the main class, create static instance EntityManagerFactory▲
EntityManagerFactory provides instances of EntityManager for connecting to the database. All the instances are configured to use the same setting as defined by the default implementation.
7.2.Code▲
//create static instance EntityManagerFactory
// Create an EntityManagerFactory when you start the application.
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence
.createEntityManagerFactory(“mysqlWithHibernate”);
8.Create a method to a record to DB Table▲
8.1.What is JPA EntityManager and EntityTransaction?▲
JPA EntityManager is used to access a database in a particular application. It is used to manage persistent entity instances, to find entities by their primary key identity, and to query over all entities.
EntityTransaction interface used to control transactions on resource-local entity managers. The EntityManager.getTransaction() method returns the EntityTransaction interface.
8.2.Code▲
//create Students
public static void addStudent(int id, String name, int age) {
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// Create a new Student object
Student student = new Student();
student.setId(id);
student.setName(name);
student.setAge(age);
// Save the student object
manager.persist(student);
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
}
8.3.Call addStudent() method▲
// 6.2 create Students
Main.addStudent(1, “John”, 22);
Main.addStudent(2, “Methew”, 20);
Main.addStudent(3, “Mike”, 25);
8.4.Run the project as Java Application▲
You can verify data in mysql. We can see three records added in student table.
9.Print list of Students▲
9.1.Create getStudents() method ▲
public static List<Student> getStudents() {
List<Student> students = null;
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// Get a List of Students
students = manager.createQuery(“SELECT s FROM Student s”, Student.class).getResultList();
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
return students;
}
9.2.Call getStudents() in main method▲
List<Student> students = getStudents();
if (students != null) {
for (Student student : students) {
System.out.println(student);
}
}
9.3.Run the project as Java Application, you will get the list of student in console▲
10.Update Student▲
10.1.Create method updateStudent()▲
public static void upateStudent(int id, String name, int age) {
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// Get the Student object
Student student = manager.find(Student.class, id);
// Change the values
student.setName(name);
student.setAge(age);
// Update the student
manager.persist(student);
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
}
10.2.Call updateStudent() in main method▲
Main.upateStudent(1, “John”, 25);
10.3.Run the project as Java Application and output can be verified in mysql▲
Now John’s age has changed from 22 to 25.
11.Delete Student▲
11.1.Create deleteStudent() method▲
public static void deleteStudent(int id) {
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// Get the Student object
Student student = manager.find(Student.class, id);
// Delete the student
manager.remove(student);
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
}
11.2.Call delete method in min method▲
Main.deleteStudent(3);
11.3.Run the project as Java Application▲
We can see one record deleted in student table, whose student id is 3.
12.Close the Entity Manager Factory▲
ENTITY_MANAGER_FACTORY.close();
Leave a Comment