Setting default values for columns in JPA
To set default values for columns in JPA (Java Persistence API), you can use the @Column
annotation and the columnDefinition
attribute.
Here is an example of how you can use the @Column
annotation to set a default value for a column in JPA:
@Entity
public class MyEntity {
@Id
@GeneratedValue
private Long id;
@Column(columnDefinition = "boolean default true")
private boolean active;
// ...
}
In this example, the active
field is annotated with the @Column
annotation, and the columnDefinition
attribute is set to "boolean default true"
. This tells JPA to use the default value true
for the active
column in the database.
You can also use the columnDefinition
attribute to specify other default values, such as numbers, strings, and dates. For example:
@Column(columnDefinition = "integer default 0")
private int count;
@Column(columnDefinition = "varchar(255) default 'Hello'")
private String message;
@Column(columnDefinition = "timestamp default current_timestamp")
private LocalDateTime createdAt;
Keep in mind that the default values specified in the columnDefinition
attribute are database-specific. The syntax of the default values may vary depending on the database you are using.
I hope this helps! Let me know if you have any questions.