1

I am learning Spring, Hibernate

I have read the following and other tutorial sources. What I understand is @Transient will prevent the object field from serializing and stop it from persisting to the database.

Transient variable in java

Transient annotation

JPA Transient annotation and JSON

My question is what if you have an object's field that you don't want to persist to database but you want the field to be retrieved when getting data from server?

For example on your MySql createDate set to CURRENT_TIMESTAMP so when a data is inserted a TIMESTAMP is then created my MySql.

MySql is set up something like this

ALTER TABLE `books` 
ADD COLUMN `dateCreated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON 
UPDATE CURRENT_TIMESTAMP AFTER `dateCreated`;

My controller is

@RequestMapping(path="/booklist", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Map<String, Object> getListBooks(@RequestParam(name="search", required=false) String search, 
                @RequestParam(name="ordering", required=false) String ordering){


    Map<String, Object> data = new HashMap<String, Object>();

    // Get list of books from server
    List<Book> books = bookDao.getBookList(search, ordering);

    System.out.println(books.get(0));

    // do other things and return map
}

My return data is

Book [id=1, name=Murach Jquery, 2rd Edition, ispn=978-1890774912, price=4.24, dateCreated=null, datePublished=null]

My Book object is as follows

@Entity
@Table(name="books")
@Component
public class Book implements Serializable{

    private static final long serialVersionUID = -2042607611480064259L;

    @Id
    @GeneratedValue
    private int id;

    @NotBlank
    private String name;

    @NotBlank
    @Size(min=2, max=16)
    private String ispn;

    @DecimalMin(value = "0.1")
    private double price;

    @Transient
    private Timestamp dateCreated;

    private Date datePublished;

    // getter and setters

}

Thank you.

Amulya K Murthy
  • 130
  • 1
  • 2
  • 15
Eric Huang
  • 1,114
  • 3
  • 22
  • 43
  • `@Transient` properties are NOT persisted to database but only added in JSON response. You may need to add `@Temporal` annotation on `dateCreated` property. – jarvo69 May 16 '17 at 06:22
  • Is it just the `createDate` you care about? – Abdullah Khan May 16 '17 at 06:44
  • 1
    Where would you retrieve it from when you have not persisted it. As anything which is not persisted goes away once the session is closed. – Mohit May 16 '17 at 06:51
  • @AbdullahKhan yes, every other field acts pretty normal sending to db and getting from db is normal just `dateCreated` is a little confusing because the date is set by MySql not in the application side. Or do you think the way I set this up is not logical and should have the date be created on the application. – Eric Huang May 16 '17 at 07:45
  • @Mohit I have updated my questions with table code in MySql. MySql will create a TIMESTAMP when data is inserted. so my controller will call on `bookDao.getBookList()` to retrieving book object. – Eric Huang May 16 '17 at 08:05

2 Answers2

1

@Transient wont help in your case.

Use @PrePersist on a method in your entity class.

@PrePersist
public void beforePersist() {
    this.dateCreated = new Date();
}

beforePersist() method annotated with @PrePersist will help you automatically initilize entity fields before you want to persist a new entity. For your case you can initialize your date property inside this method. You dont have to manually set it everytime you persist a new entity.

Now when you fetch entities from your database you will get your date property.

Also look at @PreUpdate which helps you update entity fields when you update an entity.

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
  • My timestamp is set by MySql when data is inserted. So I am not trying to set the date on the application side. You think its better to set the date on the applications side? – Eric Huang May 16 '17 at 07:20
  • I have been setting `Date` like above for the last 4-5 projects without ever getting into trouble. Besides it also removes the date dependency from your underlying Database. – Abdullah Khan May 16 '17 at 08:03
  • I see... can I ask you additional questions this is out side of the question scope but what if your application is international `new Date()` doesn't that set local machine time? rather than UTC time? – Eric Huang May 16 '17 at 08:08
  • Check out [this](http://stackoverflow.com/questions/508019/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jpa-and-hibernate/40438746#40438746) and [this](http://stackoverflow.com/a/14693148/3094731) question. – Abdullah Khan May 16 '17 at 08:15
  • Thank you so much for those links it helped me a lot. – Eric Huang May 17 '17 at 03:10
0

Use @Formula annotation for the field and just pass the column. See the example

@Formula("createDate")
private Timestamp dateCreated;
StanislavL
  • 56,971
  • 9
  • 68
  • 98