//create a book
Author author = new Author("William S. Burroughs");
Address address = new Address("Fenton Street", "931ZR2", "Leeds");
Editor editor = new Editor("Mille et Une Nuits", address);
Book book = new Book("The Yage Letters", author, editor, 1955);
//make the book persistent
pm.currentTransaction().begin();
System.out.println( "make persistent the book " + book.toString());
pm.makePersistent(book);
pm.currentTransaction().commit();
//detach the book --> "default" fetch group
//fields title and year are loaded
// fields editor and author are not loaded
Book defaultBook = (Book) pm.detachCopy(book);
System.out.println( "With the default fetchgroup:");
try{
System.out.println( "Title can be accessed: " + defaultBook.getTitle());
System.out.println( "Year can be accessed: " + defaultBook.getYear());
System.out.println( "Author should not be accessed: " + defaultBook.getAuthor().toString());
System.out.println( "Editor should not be accessed: " + defaultBook.getEditor().toString());
}
catch(Exception e){
if(e instanceof JDODetachedFieldAccessException && e.getMessage().indexOf("author") != -1)
System.out.println( "Correct exception caught: " + e.getMessage());
else
System.out.println( "Error: " + e);
}
//detach the book --> "all" fetch group
//all fields are loaded
fp.addGroup("all").removeGroup("default");
Book allBook = (Book) pm.detachCopy(book);
System.out.println( "With the all fetchgroup:");
try{
System.out.println( "Title can be accessed: " + allBook.getTitle());
System.out.println( "Year can be accessed: " + allBook.getYear());
System.out.println( "Author can be accessed: " + allBook.getAuthor().toString());
System.out.println( "Editor can be accessed: " + allBook.getEditor().toString());
}
catch(Exception e){
System.out.println( "Error: " + e);
}
}