1. Overview

In this tutorial, we’ll look into default column values in JPA.

We’ll learn how to set them as a default property in the entity as well as directly in the SQL table definition.

2. While Creating an Entity

The first way to set a default column value is to set it directly as an entity property value:

@Entity
public class User {
    @Id
    private Long id;
    private String firstName = "John Snow";
    private Integer age = 25;
    private Boolean locked = false;
}

Now, every time we create an entity using the new operator, it will set the default values we’ve provided:

@Test
void saveUser_shouldSaveWithDefaultFieldValues() {
    User user = new User();
    user = userRepository.save(user);
    
    assertEquals(user.getName(), "John Snow");
    assertEquals(user.getAge(), 25);
    assertFalse(user.getLocked());
}

There is one drawback to this solution.

When we take a look at the SQL table definition, we won’t see any default value in it:

create table user
(
    id     bigint not null constraint user_pkey primary key,
    name   varchar(255),
    age    integer,
    locked boolean
);

So, if we override them with null, the entity will be saved without any error:

@Test
void saveUser_shouldSaveWithNullName() {
    User user = new User();
    user.setName(null);
    user.setAge(null);
    user.setLocked(null);
    user = userRepository.save(user);

    assertNull(user.getName());
    assertNull(user.getAge());
    assertNull(user.getLocked());
}

3. In the Schema Definition

To create a default value directly in the SQL table definition, we can use the @Column annotation and set its columnDefinition parameter:

@Entity
public class User {
    @Id
    Long id;

    @Column(columnDefinition = "varchar(255) default 'John Snow'")
    private String name;

    @Column(columnDefinition = "integer default 25")
    private Integer age;

    @Column(columnDefinition = "boolean default false")
    private Boolean locked;
}

Using this method, the default value will be present in the SQL table definition:

create table user
(
    id     bigint not null constraint user_pkey primary key,
    name   varchar(255) default 'John Snow',
    age    integer      default 35,
    locked boolean      default false
);

And the entity will be saved properly with the default values:

@Test
void saveUser_shouldSaveWithDefaultSqlValues() {
    User user = new User();
    user = userRepository.save(user);

    assertEquals(user.getName(), "John Snow");
    assertEquals(user.getAge(), 25);
    assertFalse(user.getLocked());
}

Remember that by using this solution, we won’t be able to set a given column to null when saving the entity for the first time. If we don’t provide any value, the default one will be set automatically.

4. Conclusion

In this short article, we learned how to set default column values in JPA.

As always, the full source code is available over on GitHub.