3

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;
2
  • so, what happens when you run the above code?Did it work? Post the logs if you are getting any exceptions. Commented Feb 25, 2012 at 5:51
  • there is no exceptions but the col "date" in my sqldatabase is filled by NULL. Commented Feb 25, 2012 at 6:47

5 Answers 5

5

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();
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

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());

1 Comment

@CreationTimestamp and @Generated(GenerationTime.ALWAYS) are conflicting annotations. They should not be used together.
0

Try this as input: 2004-05-19

@Temporal(TemporalType.DATE)

private Calendar tryMe;

Comments

-1

Just use:

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

1 Comment

@CreatedDate is not a Hibernate annotation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.