Java JPA @Enity define with columnDefinition


JPA entities are nothing but POJO representations of relational databases and other database rows or documents. In the context of the relation database JPA entity represents and table row that can be persisted in the database. Entities also represent complete information of table schemas. JPA is very huge and you can refer to the official documentation here What is a JPA Entity? (oracle.com)

In this post, I am going to explain how you can define an entity’s fields more accurately with the use of columnDefinition field of @Column annotation.

Here is one simple entity with UUID type Primary Key column and BOOLEAN field.

@Entity(name= "users")
@Data
public class UserDO {
    @Id
    @GeneratedValue
    @Column(name = "id", nullable = false)
    private UUID id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "email", unique = true, nullable = false)
    private String email;

    @Column(name = "mobile_no_with_country_code", nullable = true)
    private String mobileNoWithCountryCode;

    @Column(name = "password", length = 45, nullable = true)
    private String password;

    @Column(name = "enabled", nullable = true)
    private boolean enabled;
}

With the above entity hibernate container generates a table with id column type binary in H2 DB, but I want to generate the table’s ID column with varchar(36) to store UUID in this format “abc0e4b7-932d-4410-bb98-bdf16218226d” and also I want to define a default value for enable column.

This can be done via a CREATE table script but you can also do this with @Entity object using columnDefinition as given below.

@Entity(name= "users")
@Data
public class UserDO {
    @Id
    @GeneratedValue
    @Column(name = "id", nullable = false, columnDefinition="varchar(36) PRIMARY KEY")
    private UUID id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "email", unique = true, nullable = false)
    private String email;

    @Column(name = "mobile_no_with_country_code", nullable = true)
    private String mobileNoWithCountryCode;

    @Column(name = "password", length = 45, nullable = true)
    private String password;

    @Column(name = "enabled", nullable = true, columnDefinition="boolean default true")
    private boolean enabled = true;
}

Now it will create a table with id column varchar(36) PRIMARY KEY and enable column with DEFAULT true.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.