Default column values in JPA. JPA allows to generate Schema definitions when you set hibernate. hbm2ddl. auto value to create or create-drop or update .
The default annotation for a property in the Java framework is a @ld annotation, where Hibernate assumes that the annotation is on the object's access properties and detects that it is on the field.
columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect. Follow this answer to receive notifications.
The @Basic annotation has two attributes, optional and fetch. Let's take a closer look at each one. The optional attribute is a boolean parameter that defines whether the marked field or property allows null. It defaults to true.
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;
Use hibernate annotation.
@ColumnDefault("-1")
private Long clientId;
Recreate the table if it already exists for the changes to take effect.
You can use @PrePersist
anotation and set the default value in pre-persist stage.
Something like that:
//... some code
private String myProperty;
//... some code
@PrePersist
public void prePersist() {
if(myProperty == null) //We set default value in case if the value is not set yet.
myProperty = "Default value";
}
// property methods
@Column(nullable = false) //restricting Null value on database level.
public String getMyProperty() {
return myProperty;
}
public void setMyProperty(String myProperty) {
this.myProperty= myProperty;
}
This method is not depend on database type/version underneath the Hibernate. Default value is set before persisting the mapping object.
what about just setting a default value for the field?
private String _foo = "default";
//property here
public String Foo
if they pass a value, then it will be overwritten, otherwise, you have a default.
If you want to do it in database:
Set the default value in database (sql server sample):
ALTER TABLE [TABLE_NAME] ADD CONSTRAINT [CONSTRAINT_NAME] DEFAULT (newid()) FOR [COLUMN_NAME]
Mapping hibernate file:
<hibernate-mapping ....
...
<property name="fieldName" column="columnName" type="Guid" access="field" not-null="false" insert="false" update="false" />
...
See, the key is insert="false" update="false"
If you want to set a default entity property value, then you can initialize the entity field using the default value.
For instance, you can set the default createdOn
entity attribute to the current time, like this:
@Column(
name = "created_on"
)
private LocalDateTime createdOn = LocalDateTime.now();
If you are generating the DDL schema with JPA and Hibernate, although this is not recommended, you can use the columnDefinition
attribute of the JPA @Column
annotation, like this:
@Column(
name = "created_on",
columnDefinition = "DATETIME(6) DEFAULT CURRENT_TIMESTAMP"
)
@Generated(GenerationTime.INSERT)
private LocalDateTime createdOn;
The @Generated
annotation is needed because we want to instruct Hibernate to reload the entity after the Persistence Context is flushed, otherwise, the database-generated value will not be synchronized with the in-memory entity state.
Instead of using the columnDefinition
, you are better off using a tool like Flyway and use DDL incremental migration scripts. That way, you will set the DEFAULT
SQL clause in a script, rather than in a JPA annotation.
If you are using JPA with Hibernate, then you can also use the @ColumnDefault
annotation, like this:
@Column(name = "created_on")
@ColumnDefault(value="CURRENT_TIMESTAMP")
@Generated(GenerationTime.INSERT)
private LocalDateTime createdOn;
If you are using JPA with Hibernate and want to set the creation timestamp, then you can use the @CreationTimestamp
annotation, like this:
@Column(name = "created_on")
@CreationTimestamp
private LocalDateTime createdOn;
One solution is to have your getter check to see if whatever value you are working with is null (or whatever its non-initialized state would be) and if it's equal to that, just return your default value:
public String getStringValue(){
return (this.stringValue == null) ? "Default" : stringValue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With