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.
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.