Date field is not updated [message #758623] |
Wed, 23 November 2011 18:01  |
Eclipse User |
|
|
|
Howdy Guys!
Just bumped into some interesting stuff. It seems that I cannot update a java.util.Date field (setting a new Date object) if before this setter method I'll try to invoke 'setTime()' on old date object.
I attach the code which shows this behaviour.
I can only assume that it's some kind of prevention mechanism to forbid users to invoke getDateField().setTime(-). In this way, without preparing defensive copy in the getter, user could be able to change the field's state using just the getter.
It seems that EclipseLink is able to find such situations and invalidates all changes made to this field EVEN if the following changes are correct.
Can anyone confirm this behaviour?
Is this JPA specification requirement or just EclipseLink feature?
Entity
@Entity
public class MyEntity {
@Id
@GeneratedValue
private Integer id;
@Temporal(TemporalType.TIMESTAMP)
private Date created = new Date();
public Integer getId() {
return id;
}
@Override
public String toString() {
return "MyEntity [getId()=" + getId() + ", getCreated()=" + getCreated();
}
public Date getCreated() {
// no defensive copy here - return straight reference
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}
Simple service operations (most interesting is the modifyObject(-) method.
@Stateless
public class MyService {
@PersistenceContext
EntityManager em;
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Integer persistObject() {
MyEntity entity = new MyEntity();
em.persist(entity);
System.out.println("[persistObject()]" + entity);
return entity.getId();
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public MyEntity readObject(Integer id) {
MyEntity entity = em.find(MyEntity.class, id);
System.out.println("[readObject()]" + entity);
return entity;
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Integer modifyObject(Integer id) {
MyEntity entity = em.find(MyEntity.class, id);
// Try to change date state without changing its reference.
entity.getCreated().setTime(0L);
// And now try use regular setter to set new date
Date d = new Date(0L);
entity.setCreated(d);
// Pre-update state is correct - Date is 01.01.1970
System.out.println("[modifyObject()]" + entity);
return entity.getId();
}
}
Service methods invocation
Integer id = service.persistObject();
// Date is reflecting 'now' - correct
MyEntity entity = service.readObject(id);
// Pre-update state is correct - 01.01.1970
id = service.modifyObject(id);
// Post-update state is incorrect - back to 'now' instead of 01.01.1970
service.readObject(id);
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.25089 seconds