Default value not working in sleep mode

I use columnDefinitionto specify the default value for the column, however it does not save the default value, it only stores null,

Please help with this, below is my code

private String sourceFrom;
@Column(name = "SourceFrom", columnDefinition = "varchar(15) default 'Case'")
public String getSourceFrom() {
    return sourceFrom;
}

public void setSourceFrom(String sourceFrom) {
    this.sourceFrom = sourceFrom;
}
+3
source share
4 answers

@Column.columnDefinitionused during the DDL phase to create your table and NOT during normal program operation; you will probably have to work with @DynamicInsert/@DynamicUpdate: these annotations insert (or update) only those properties that you set in the POJO, and allow RDBMS to manage other fields.
A small example

@Entity
class MyTable {
  @Id
  private int code;
  @Column(name = "SourceFrom", columnDefinition = "varchar(15) default 'Case'")
  private String sourceFrom; 
}

and this is the generated code from the DDL phase

create table mytable (code integer not null,SourceFrom varchar(15) default 'Case')

MyTable t = new MyTable();
t.setCode(10);
session.save(t);

will make this statement

insert into mytable (code, SourceFrom) values (10,NULL)

MyTable t = new MyTable();
t.setCode(10);
t.setSourceFrom("MANUAL INSERT");
session.save(t);

will make this statement

insert into mytable (code, SourceFrom) values (10,'MANUAL INSERT')

MyTable @DynamicInsert,

insert into mytable (code) values (10)

, SourceFrom , , , ('Case').

( , @PrePersist ) - .

+6

, , , . -

@PrePersist
void preInsert() {
   if ( getSourceFrom() == null ) { setSourceFrom( "Case" ); }
}

,

+2

, Hibernate . , ( L2).

If you load an object, it comes from the Hibernate cache, not from the database.

To resolve this issue, call one of the following:

  • update object session.refresh(yourEntity)
  • initialize it with java instead of the default value
  • use @PrePersistlistener
0
source

Enter the default values ​​towards the database. If you want to use it in entity mapping, just set the default value below

private String sourceFrom = "Case";

0
source

All Articles