Javax, @Defaultvalues, @Prepersistent, @Preupdate

Asked

Viewed 88 times

1

I’m learning to play with Javax, and persistence of Java and I 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 that in my Template 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

1 answer

1


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

@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 runs before the entity is updated.

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

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

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

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

See [Hibernate] which is one of JPA implementations: https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html

  • What is Defaultvalue for? And also, as I saw Prepersist and Preupdate are methods, correct ?

  • @Felipejunges Yes, Voce puts @PrePersist and @PreUpdate in a method and within it you change the values of Entity as you like. The annotation DefaultValue there is no

Browser other questions tagged

You are not signed in. Login or sign up in order to post.