Java ENUM Mapping in postgres using Spring Data JPA and Hibernate.

Java ENUM Mapping in postgres using Spring Data JPA and Hibernate.

Maheshwar Ligade's photo
Maheshwar Ligade
·Jun 12, 2022·

3 min read

Table of contents

  • Introduction:
  • DB Script:
  • Properties:
  • Implementation:
  • Conclusion:
  • Complete Source Code:
  • More such articles:

In this article, you are going to learn how to map Java enum in the Postgres database using ORM implementation such as Hibernate with Spring Data JPA.

If you don't know how to set up Postgres using docker in local, please see the below video.

Postgres setup in local using docker.

Introduction:

Let us set the plot, you have a requirement to create a custom type such as product type, in PostgreSQL, Let’s call it product_type. It’s an enum defined as follows: electronics, cosmetic, edible, etc.

create_type.png

Once you have created this product_type, then while inserting data into the products table with some fields like id, product_name, price, tag, and product_type.

producttype.png

Let us create the project go to start.spring.io OR use any editor or IDE.

image.png

Create simple application with Controller, Service and Data access layer.

DB Script:

Database script to create the table, enum type and sample insert script for record insertion.


CREATE TABLE IF NOT EXISTS public.products
(
    id bigint NOT NULL,
    product_name text COLLATE pg_catalog."default",
    price bigint,
    tag text COLLATE pg_catalog."default",
    product_type product_type,
    CONSTRAINT products_pkey PRIMARY KEY (id)
);

-- insert some records
INSERT INTO public.products(
    id, product_name, price, tag, product_type)
    VALUES (?, ?, ?, ?, ?);

-- enum type

CREATE TYPE product_type AS ENUM
    ('electronics', 'cosmetic', 'edible');

Properties:

Properties file contains properties to make database connection.

## default connection pool
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

## PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=pass

#drop n create table again, good for testing, comment this in production
spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

Implementation:

In this example, created sample Controller, service and data access layer coding. To handle the enum in java, you have to first creat the custom enumtype by extending the hibernate EnumType.

public class PgSQLEnumType extends EnumType{

    public void nullSafeSet(
        PreparedStatement ps, Object value, int index,
        SharedSessionContractImplementor session
    ) throws HibernateException, SQLException{

        ps.setObject(index,value!=null? ((Enum)value).name():null,Types.OTHER);
    }

}

Then you have to create the Java enum which will represent, your Postgres enum.

public enum ProductType {

    electronics,cosmetic,edible;

}

Once this is done then, you can go ahead and write down the entity class with annotation @TypeDef.

@Entity
@Table(name = "products")
@TypeDef(
    name = "product_type",
    typeClass = PgSQLEnumType.class
)
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;


    private String product_name;

    private float price;

    private String tag;

    @Enumerated(EnumType.STRING)
    @Column(name = "product_type")
    private ProductType type;
//setter and getter
}

On the entity layer, you have to add @TypeDef annotation with two attribute fields, the first one is the name of the column and the second one is the type of EnumType class name.

These three parts are going to help you to handle the enum efficiently in Postgres with spring boot and Spring Data JPA.

Conclusion:

In this article, you learned how to handle enums efficiently in Spring Data JPA and hibernate. This is the one way, which I know, if you know or use any other best way, Let me know in the comment section below.

Complete Source Code:

Download the complete source code.

git clone https://github.com/maheshwarLigade/spring-boot-examples
cd spring-boot-examples\postgresdemo
-- run the spring boot Gradle project

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

==========================**=========================

If this article adds any value for you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this