views:

126

answers:

2

Hey folks,

I try to save the date of creation of my entity. I have found that approach. I tried to implement it but the date doesn't reach my db-table.

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;

@Entity
public class Project implements Serializable {

 private static final long serialVersionUID = 7620757776698607619L;

 @Id
 int id;
 String title;
 Date created;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getTitle() {
  return title;
 }

 @PrePersist
 protected void onCreate() {
   created = new Date();
 }

 public Date getCreated() {
  return created;
 }

}

Only title is being saved. The field for data is empty :-(

Where is my mistake? Thank you for helping me.


Update

I tried to add the annotation of pascal but it didn't help. Is it possible that I should use sql.date istead of utils.date. I try this but I can't find how to get today's date...

A: 

I wonder if the lack of setter for the created date is not a problem. As an aside, I would also define a Temporal annotation on the created date to save the date and time. Something like this:

@Entity
public class Project implements Serializable {

    @Id
    private int id;
    private String title;
    @Temporal(TemporalType.TIMESTAMP)
    private Date created;

    ...

    public Date getCreated() {
        return created;
    }
    public void setCreated(Date created) {
        this.created = created;
    }

    @PrePersist
    protected void onCreate() {
        created = new Date();
    }

}
Pascal Thivent
A: 

I didn't make it but I have found another way:

@Entity
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private Date created;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }
}

That's my EntityObject...I left it the standard way and put the logic into my controller layer which lies above:

public String saveNewProject() {
    projectData.getProjectDTO().setCreated(new Date());
    projectService.addProject(projectData.getProjectDTO());

Actually I like it more that way, because if I substitude the persistence layer some day I won't have to transfer the logic... cheers

Sven