Hibernate 5 – Enum Type Mapping Example

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 –

  1. @Enumerated(EnumType.ORDINAL)

    Store the enum values according the ordinal position (i.e. 0 , 1, 2 … ) of enum value.

  2. @Enumerated(EnumType.STRING)

    Store the enum values according to the name of enum value. The default is EnumType.ORDINAL.

  3. Let’s look at how to map enum types using @javax.persistence.Enumerated annotation with below snippets.
  4. Consider the following enum types –
packagenet.ducatindia.hibernate.entity;

publicenumProjectStatus {
    OPEN,
    INPROGESS,
    RESUME,
    COMPLETED,
    CLOSED;
}

Let’s use and map this enum in Project entity class –

@Entity
@Table(name = "project")
public class Project {

    @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
privateint id;

@Column(name = "project_name")
private String projectName;

@Enumerated(EnumType.STRING)
@Column(name = "project_status")
privateProjectStatusprojectStatus;

    // getter and setters
}

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.ducatindia.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>

Create Enum – ProjectStatus.java

Create ProjectStatus enum class and add following code to it.

packagenet.ducatindia.hibernate.entity;

publicenumProjectStatus {
OPEN, INPROGESS, RESUME, COMPLETED, CLOSED;
}

A simple Persistent class should follow some rules:

  • A no-arg constructor:

    It is recommended that you have a default constructor at least package visibility so that hibernate can create the instance of the Persistent class by newInstance() method.

  • Provide an identifier property:

    It is better to assign an attribute as id. This attribute behaves as a primary key in a database.

  • Declare getter and setter methods:

    The Hibernate recognizes the method by getter and setter method names by default.

  • Prefer non-final class:

    Hibernate uses the concept of proxies, that depends on the persistent class. The application programmer will not be able to use proxies for lazy association fetching.

Create a Project entity class under net.javaguides.hibernate.entity package as follows.

packagenet.ducatindia.hibernate.entity;

importjavax.persistence.Column;
importjavax.persistence.Entity;
importjavax.persistence.EnumType;
importjavax.persistence.Enumerated;
importjavax.persistence.GeneratedValue;
importjavax.persistence.GenerationType;
importjavax.persistence.Id;
importjavax.persistence.Table;

@Entity
@Table(name = "project")
public class Project {

    @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
privateint id;

@Column(name = "project_name")
private String projectName;

@Enumerated(EnumType.STRING)
@Column(name = "project_status")
privateProjectStatusprojectStatus;

publicintgetId() {
return id;
    }

public void setId(int id) {
        this.id = id;
    }

public String getProjectName() {
returnprojectName;
    }

public void setProjectName(String projectName) {
this.projectName = projectName;
    }

publicProjectStatusgetProjectStatus() {
returnprojectStatus;
    }

public void setProjectStatus(ProjectStatusprojectStatus) {
this.projectStatus = projectStatus;
    }
}

Here 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.

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 Project entity to the MetadataSources for mapping as follows.

Dialects are an important feature in Hibernate. They enable you to implement a database-independent persistence layer by transparently adapting your mappings and queries. So, make sure to always use the correct dialect for your database system and version.

packagenet.ducatindia.hibernate.util;

importjava.util.Properties;

importorg.hibernate.SessionFactory;
importorg.hibernate.boot.registry.StandardServiceRegistryBuilder;
importorg.hibernate.cfg.Configuration;
importorg.hibernate.cfg.Environment;
importorg.hibernate.service.ServiceRegistry;

importnet.ducatindia.hibernate.entity.Student;

publicclassHibernateUtil {
privatestaticSessionFactorysessionFactory;
publicstaticSessionFactorygetSessionFactory() {
if (sessionFactory==null) {
try {
Configurationconfiguration=newConfiguration();

// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings =newProperties();
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);

ServiceRegistryserviceRegistry=newStandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

sessionFactory=configuration.buildSessionFactory(serviceRegistry);
            } catch (Exception e) {
e.printStackTrace();
            }
        }
returnsessionFactory;
    }
}

Create ProjectDao Class

Let’s create a separate ProjectDao class to separate out hibernate related stuff.

packagenet.ducatindia.hibernate.dao;

importjava.util.List;

importorg.hibernate.Session;
importorg.hibernate.Transaction;

importnet.ducatindia.hibernate.entity.Project;
importnet.ducatindia.hibernate.util.HibernateUtil;

publicclassProjectDao {
publicvoidsaveProject(Projectproject) {
try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
Transactiontransaction=session.beginTransaction();
// save the project object
session.save(project);
// commit transaction
transaction.commit();
        }
    }

publicList< Project>getProjects() {
try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
returnsession.createQuery("from Project", Project.class).list();
        }
    }
}

Create the main App class and Run an Application

Let’s test Hibernate application to connect MySQL database.

packagenet.ducatindia.hibernate;

importjava.util.List;

importnet.ducatindia.hibernate.dao.ProjectDao;
importnet.ducatindia.hibernate.entity.Project;
importnet.ducatindia.hibernate.entity.ProjectStatus;

publicclassMainApp {
publicstaticvoidmain(String[] args) {
ProjectDaoprojectDao=newProjectDao();
Projectproject=newProject();
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());
        });
    }
}

Copyright 1999- Ducat Creative, All rights reserved.

Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.