jpa-default-column-values
Default Column Values in JPA
1. Introduction
We’ll learn how to set them in as a default property in the entity as well as directly in the SQL table definition.
2. While Creating an Entity
@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’ll create an entity using the new operator it’ll 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 of 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. Summary
As always, the full source code is available over on GitHub.