Javax, @DefaultValues, @PrePersistent, @PreUpdate

1

I'm learning to tinker with Javax, and Java persistence and want to know if there's any way to leave a default value for the database.

Example in SQL:

variacao TIMESTAMP DEFAULT CURRENT_TIMESTAMP

How would I do this in my Model code?

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;

@NotNull
@Column(name="nota")
private int nota;

@NotNull
@Column(name="data")
private Timestamp data;

@Column(name="comentario")
private String comentario;

@Column(name="evento_id")
private Evento evento_id;

@Column(name="pessoa_id")
private Pessoa pessoa_id;

1) What is the difference between the following items? a) @DefaultValues b) @PrePersistent c) @PreUpdate

2) And which one would I use for this case? a) @DefaultValues b) @PrePersistent c) @PreUpdate

    
asked by anonymous 01.09.2017 / 22:16

1 answer

1

So I understand you are using JPA, in this case if you prefer to let the default value be generated by the bank use this:

@Column(name = "DATA_ATUALIZACAO", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")

This will only work if you let JPA create the tables, or export the table creation script.

  

1) What is the difference between the following items?

     

@PrePersist

Callback is executed before the entity is persisted.

  

@PreUpdate

Callback is executed before the entity is updated.

  

2) And which one would I use for this case?

This will depend on the purpose of your column, for example:

  • If your DATA column to store the registration date would have to use @PrePersist ;

  • If your DATA column you have to store the update date you would have to use @PreUpdate ;

Please see in [hibernate] which is one of the JPA implementations: link

    
02.09.2017 / 06:03