Core Java Data Objects
4.2 Finding Out about an Object's State
The previously mentioned seven states transient , persistent-new , persistent-new-deleted , hollow , persistent-clean , persistent-dirty , and persistent-deleted are mandatory for all JDO implementations , although there is no API to get the internal state of an instance used within the JDO implementation. The exact state of a JDO instance is known only by the JDO implementation, and some states might not even be implemented by some vendors . The JDO states are defined in a behavioral manner. Nevertheless, some methods let us interrogate the persistence attributes coupled with the object and find information about the object's state. These static methods are in the JDOHelper class:
boolean isDeleted(Object o) boolean isDirty(Object o) boolean isNew(Object o) boolean isPersistent(Object o) boolean isTransactional(Object o) There is no method to find out whether an object is hollow. It is a vendor's choice how to handle the lazy on-demand reading of fields and objects to alleviate the responsibility from the programmer. Later in this chapter, another way is shown to get information about an object's hollow state. The following class prints the persistence flags of an instance by using the JDOHelper class:
public class Example01 { public static void printInfo(String msg, Object obj) { StringBuffer buf = new StringBuffer(msg); if (JDOHelper.isPersistent(obj)) buf.append(" persistent"); if (JDOHelper.isNew(obj)) buf.append(" new"); if (JDOHelper.isDirty(obj)) buf.append(" dirty"); if (JDOHelper.isDeleted(obj)) buf.append(" deleted"); if (JDOHelper.isTransactional(obj)) buf.append(" transactional"); System.out.println(buf.toString()); } The following lines of code illustrate states and methods that we have used up to now:
public static void main(String args[]) { PersistenceManager pm = pmf.getPersistenceManager(); pm.currentTransaction().begin(); Book book = new Book(); printInfo("a new book ",book); pm.makePersistent(book); printInfo("persistent book ",book); pm.deletePersistent(book); printInfo("deleted book ",book); pm.currentTransaction().rollback(); printInfo("rolled back ",book); pm.currentTransaction().begin(); pm.makePersistent(book); pm.currentTransaction().commit(); printInfo("new commit ",book); pm.currentTransaction().begin(); String title = book.title; printInfo("read field ",book); String title = "new "+book.title; printInfo("modified field ",book); pm.deletePersistent(book); printInfo("deleted book ",book); pm.currentTransaction().commit(); printInfo("last commit ",book); } } When the example is run, it prints the following:
a new Book: dirty persistent book: persistent new dirty deleted book: persistent new dirty deleted rolled back: dirty new commit: persistent read field: persistent modified field: persistent dirty deleted book: persistent dirty deleted last commit: dirty |