A bean has been modified, how can I know which fields has been modified?

211 views
Skip to first unread message

Freewind

unread,
Jan 5, 2011, 10:39:24 PM1/5/11
to Ebean ORM
I have a class named `Question`, I want to save the changed fields
when it saved.

@Entity
public class Question {

@Id
public Long id;
public String title;
public String content;

@PreUpdate
void saveChanges() {
Question ori = Ebean.find(Question.class, this.id);
String oriTitle = ori.title;
String oriContent = ori.content;
// !!!!!!!
// But the oriTitle and oriContent are the same as
current !!!
}

}

In the @PreUpdate method, nomatter how I get the original bean, the
filed values are the modified ones. Is there anyway to get the
original values?

Rob Bygrave

unread,
Jan 6, 2011, 2:02:53 AM1/6/11
to eb...@googlegroups.com

@PreUpdate is not going to do anything with Ebean - it is not supported.

You need to use BeanPersistController instead. Looking at BeanPersistController and BeanPersistRequest which provides the updated properties and the loaded properties as well as the old values. Specifically I would not invoke another query to read the old values... just get them from BeanPersistRequest.  These objects are in the com.avaje.ebean.event package.

http://www.avaje.org/static/javadoc/pub/com/avaje/ebean/event/BeanPersistController.html

Daryl Stultz

unread,
Jan 6, 2011, 8:03:01 AM1/6/11
to Ebean ORM

On Jan 5, 10:39 pm, Freewind <nowind...@gmail.com> wrote:
> I have a class named `Question`, I want to save the changed fields
> when it saved.

Rob's response seems to suggest you want to get access to the original
values. Your thread title doesn't make that clear. So if all you want
to know is which fields are dirty you can do something like this. This
is my unit test for exploring Ebean's dirty field tracking:

Role role1 = SetupUtils.insertRole();

EntityBean eb = (EntityBean) role1;
EntityBeanIntercept ebi = eb._ebean_getIntercept();
assertFalse(ebi.isDirty());
String origName = role1.getName();
role1.setName(origName);
assertFalse(ebi.isDirty());
assertNull(ebi.getChangedProps()); // null if "clean"
role1.setName("dirty!");
assertTrue(ebi.isDirty());
assertTrue(ebi.getChangedProps().contains("name"));
role1.setName(origName); // setting it back to original doesn't
"clean" it
assertTrue(ebi.isDirty());

(Note that setting a value back to the original leaves it dirty. I
would like it to be clean.)

/Daryl

Freewind

unread,
Jan 6, 2011, 8:11:29 AM1/6/11
to Ebean ORM
Thank you all very much !!!
Reply all
Reply to author
Forward
0 new messages