How to Add Default Column Values in JPA

You can add default column values in JPA in two ways. Firstly, set values just like setting a value to any variable (specifically here you are setting the entity property value). Next, by the explicit setting of column definition default value using @Column annotation.

Here I will show how both these two can be achieved. In the examples given below, I will set the default value true to the column isFirstLogin in the entity User.

Set Default Value While Creating Entity

@Table(name = "sa_user")
public class User{
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;
    @NotBlank(message = "Username is required")
    private String username;

    // Setting the default value of isFirstLogin column as true
    private Boolean isFirstLogin = true;

}

Set Default Value in Schema Definition

@Table(name = "sa_user")
public class User{
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;
    @NotBlank(message = "Username is required")
    private String username;

    // Setting the default value of isFirstLogin column as true
    @Column(columnDefinition = "boolean default true")
    private Boolean isFirstLogin;

}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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