socrateisabot
socrateisabot

Reputation: 847

How to auto insert Current DATE in SQL with Java / Hibernate

I need to add automatically the current date into my Database when I create a new OperantionBank. I'm using Hibernate. Thanks

import java.io.Serializable;
import java.sql.Date;
import javax.persistence.*;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

@Entity
public class OperationBank implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String wordring;

private Double amount;

@Generated(GenerationTime.ALWAYS)
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateoperation = new java.sql.Date(new java.util.Date().getTime());

@OneToOne
private Account account;

Upvotes: 3

Views: 41681

Answers (5)

Mezen sboui
Mezen sboui

Reputation: 39

Try this as input: 2004-05-19

@Temporal(TemporalType.DATE)

private Calendar tryMe;

Upvotes: 0

For create, you need to use:

@CreationTimestamp
@Generated(GenerationTime.ALWAYS)
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateoperation = new java.sql.Date(new java.util.Date().getTime());

Upvotes: 0

ankit
ankit

Reputation: 2845

Just use:

@CreatedDate
@Temporal(TemporalType.DATE)
@Column(name = "start_date")
private Date startDate;

Upvotes: -1

elusive-code
elusive-code

Reputation: 1183

While Emil H is correct, I would like to add that way you did should work too.

It didn't most likely because the name of the column (you said in comment it is "date") doesn't match name of the field ("dateoperation").

You could either rename field/column, or add annotation:

@Column(name = "date")

Also note: you don't have to use java.sql.Date, it should work with java.util.Date just as well.

import java.util.Date;
...

@Column(name = "date")
private Date dateoperation = new Date();

Upvotes: 5

Emil L
Emil L

Reputation: 21111

This answer might help you:

https://stackoverflow.com/a/221827/355499

In essence you use @PrePersist and/or @PreUpdate annotation to generate the dates when needed.

Upvotes: 3

Related Questions