Transient Classes

Some of the classes are not supposed to be persistent. Of course you can avoid saving their instances in your code and mark all their occurrences in another classes as transient (Java/.NET). But that needs some attention and additional coding. You can achieve the same result in an easier way using TransientClass interface:

Java:

com.db4o.types.TransientClass

TransientClass is a marker interface, which guarantees that the classes implementing it will never be added to the class metadata. In fact they are just skipped silently by db4o persistence mechanism.

An example of the TransientClass implementation is db4o object container (we do not need to save a database into itself).

Let's look how it works on an example. We will create a simplest class implementing TransientClass interface:

NotStorable.java
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02 03package com.db4odoc.selectivepersistence; 04 05import com.db4o.types.TransientClass; 06 07 08public class NotStorable implements TransientClass { 09 10 public String toString(){ 11 return "NotStorable class"; 12 } 13}

NotStorable class will be used as a field in two test objects: Test1 and Test2.

In our example we will use the default configuration and save Test1 and Test2 objects just as usual:

TransientClassExample.java: saveObjects
01private static void saveObjects() { 02 new File(DB4O_FILE_NAME).delete(); 03 ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 04 try { 05 // Save Test1 object with a NotStorable class field 06 Test1 test1 = new Test1("Test1", new NotStorable()); 07 container.set(test1); 08 // Save Test2 object with a NotStorable class field 09 Test2 test2 = new Test2("Test2", new NotStorable(), test1); 10 container.set(test2); 11 } finally { 12 container.close(); 13 } 14 }

Now let's try to retrieve the saved objects:

TransientClassExample.java: retrieveObjects
01private static void retrieveObjects() { 02 ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 03 try { 04 // retrieve the results and check if the NotStorable 05 // instances were saved 06 ObjectSet result = container.get(null); 07 listResult(result); 08 } finally { 09 container.close(); 10 } 11 }
If you will run the example code you will see that all the instances of NotStorable class are set to null.