Setting default values for columns in JPA
Actually it is possible in JPA, although a little bit of a hack using the columnDefinition
property of the @Column
annotation, for example:
@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")
Default value declared in JPA @Column( columnDefinition ... ) not set when persisted
Null value is because JPA explicitly inserts a null
value in to that column if no special handling is implemented. The columnDefinition
does make the column creation with DEFAULT but it does not make JPA aware of/or obey it afterwards.
And it is a nullable column so there is no error. See what happens in plain SQL, think of this table:
create table example (
col1 bigint default 42,
col2 bigint default 99
);
Then make an insert like:
insert into example (col1) values (null);
then selecting:
select * from example;
would show result like:
col1 | col2
------+------
(null) | 99
If you need to have default values managed in the java side you need some special stuff in the Java side.
See for example this question and note that the accepted answer is not the working one but this answer. So setting the value when class is instantiated:
private Long valueX = 0;
Another way is as this answer for different question suggests, using @PrePersist
:
@PrePersist
void prePersist() {
if (this.valueX == null)
this.valueX = 0;
}
How to set a default entity property value with Hibernate
If you want a real database default value, use columnDefinition
:
@Column(name = "myColumn", nullable = false, columnDefinition = "int default 100")
Notice that the string in columnDefinition
is database dependent. Also if you choose this option, you have to use dynamic-insert
, so Hibernate
doesn't include columns with null
values on insert. Otherwise talking about default is irrelevant.
But if you don't want database default value, but simply a default value in your Java code, just initialize your variable like that - private Integer myColumn = 100;
Related Topics
Most Efficient Way to Increment a Map Value in Java
Why Can't We Use 'This' Keyword in a Static Method
Swingutilities.Invokelater() Why Is It Needed
How to Generate Jaxb Classes from Xsd
Allowing Java to Use an Untrusted Certificate for Ssl/Https Connection
Getting the Class Name from a Static Method in Java
Execute Method on Startup in Spring
Why Invoke Thread.Currentthread.Interrupt() in a Catch Interruptexception Block
Lombok Annotations Do Not Compile Under Intellij Idea
Multi-Project Test Dependencies with Gradle
How to Draw the Same Moving Image Multiple Times
Jax-Rs/Jersey How to Customize Error Handling
Quickest Way to Find Missing Number in an Array of Numbers