Hibernate Framework Architecture and Basics
Hibernate Hello World Tutorial
Hibernate XML Configuration Example
Hibernate Java Configuration Example
Hibernate Transaction Management
Hibernate/JPA - Primary Key Generation Strategies
JPA and Hibernate Cascade Types
Hibernate - Save an Entity Example
Hibernate - Persist an Entity Example
Hibernate - saveOrUpdate() Method Example
Hibernate - get(), load() and byId() Method
Hibernate - merge() Example
Hibernate - Delete or Remove an Entity Example
Hibernate - load() Method Example
Hibernate Session.clear() Method Example
Hibernate One to One Mapping
Hibernate One to Many Mapping
Hibernate Many to Many Annotation
Hibernate One to Many CRUD Example
Hibernate One to One CRUD Example
Hibernate Inheritance Mapping
Hibernate Query Language
Hibernate CRUD Operations Example
Hibernate Session Interface Methods
JSP Servlet Hibernate CRUD Example
Hibernate Registration Form Example
Login Form using JSP + Servlet + Hibernate + MySQL
More .........
In this article, we will show you how a Java enum type is persisted into a database in hibernate applications.
An enum type is mapped to a database via the @javax.persistence.Enumerated annotation.
There are two strategies to store enum values in the database -
- @Enumerated(EnumType.ORDINAL) → Store the enum values according the ordinal position (i.e. 0 , 1, 2 … ) of enum value.
- @Enumerated(EnumType.STRING) → Store the enum values according to the name of enum value. The default is EnumType.ORDINAL.
Let's look at how to map enum types using @javax.persistence.Enumerated annotation with below snippets.
Consider the following enum types -
package net.javaguides.hibernate.entity;
public enum ProjectStatus {
OPEN,
INPROGESS,
RESUME,
COMPLETED,
CLOSED;
}
Let's use and map this enum in a Project entity class -
@Entity
@Table(name = "project")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "project_name")
private String projectName;
@Enumerated(EnumType.STRING)
@Column(name = "project_status")
private ProjectStatus projectStatus;
// getter and setters
}
Let's develop a simple hibernate application to demonstrate enum type mapping with a database table column.
Technologies and tools used
- Hibernate 5.3.7.Final
- IDE - Eclipse Noen
- Maven 3.5.3
- JavaSE 1.8
- MySQL - 8.0.13
Development Steps
- Create a Simple Maven Project
- Project Directory Structure
- Add jar Dependencies to pom.xml
- Create Enum - ProjectStatus.java
- Creating the JPA Entity Class(Persistent class)
- Create a Hibernate configuration file - Java Configuration
- Create ProjectDao Class
- Create the Main class and Run an Application
1. Create a Simple Maven Project
Use the How to Create a Simple Maven Project in Eclipse article to create a simple Maven project in Eclipse IDE.
2. Project Directory Structure
The project directory structure for your reference -
3. Add jar Dependencies to pom.xml
<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>
<parent>
<groupId>net.javaguides.hibernate</groupId>
<artifactId>hibernate-tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>hibernate-enum-type-example</artifactId>
<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.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.7.Final</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>
4. Create Enum - ProjectStatus.java
Create ProjectStatus enum class and add the following code to it.
package net.javaguides.hibernate.entity;
public enum ProjectStatus {
OPEN, INPROGESS, RESUME, COMPLETED, CLOSED;
}
5. Creating the JPA Entity Class(Persistent class)
Let's create a Project persistent class that is mapped to a database table.
package net.javaguides.hibernate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "project")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "project_name")
private String projectName;
@Enumerated(EnumType.STRING)
@Column(name = "project_status")
private ProjectStatus projectStatus;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public ProjectStatus getProjectStatus() {
return projectStatus;
}
public void setProjectStatus(ProjectStatus projectStatus) {
this.projectStatus = projectStatus;
}
}
Here is the EnumType.STRING strategy is used for the ProjectStatus field so the project_status column can hold either PERMANENT or COMMUNICATION value.
Similarly the EnumType.ORDINAL strategy can be used for project_status column can hold either 0 or 1 value.
6. Create a Hibernate configuration file - Java Configuration
The HibernateUtil Java configuration file contains information about the database and mapping file. Create a helper class to bootstrap hibernate and add the Project entity to the MetadataSources for mapping as follows.
package net.javaguides.hibernate.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import net.javaguides.hibernate.entity.Student;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3306/hibernate_db?useSSL=false");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "root");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Project.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
Create ProjectDao Class
Let's create a separate ProjectDao class to separate out hibernate related stuff.
package net.javaguides.hibernate.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import net.javaguides.hibernate.entity.Project;
import net.javaguides.hibernate.util.HibernateUtil;
public class ProjectDao {
public void saveProject(Project project) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
Transaction transaction = session.beginTransaction();
// save the project object
session.save(project);
// commit transaction
transaction.commit();
}
}
public List < Project > getProjects() {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("from Project", Project.class).list();
}
}
}
7. Create the main App class and Run an Application
Let's test Hibernate application to connect MySQL database.
package net.javaguides.hibernate;
import java.util.List;
import net.javaguides.hibernate.dao.ProjectDao;
import net.javaguides.hibernate.entity.Project;
import net.javaguides.hibernate.entity.ProjectStatus;
public class MainApp {
public static void main(String[] args) {
ProjectDao projectDao = new ProjectDao();
Project project = new Project();
project.setProjectName("TPO");
project.setProjectStatus(ProjectStatus.INPROGESS);
projectDao.saveProject(project);
List < Project > projects = projectDao.getProjects();
projects.forEach(s - > {
System.out.println(s.getProjectName());
System.out.println(s.getProjectStatus());
});
}
}
Output
GitHub Repository
The complete source code of this article is available on my GitHub Repository - https://github.com/RameshMF/Hibernate-ORM-Tutorials
Conclusion
In this article, we have shown you how to use the Java enum type to persist a JPA entity into a database.
You can learn more about Hibernate ORM Framework at Hibernate Tutorial
References
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Useful tutorial.
ReplyDelete