This topic applies to Java version only
Let's use the following class as an example of a class which can not be stored clearly with db4o.
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02
package com.db4odoc.translators; 03
04
public class NotStorable { 05
private int id; 06
07
private String name; 08
09
private transient int length; 10
11
public NotStorable(int id, String name) { 12
this.id = id; 13
this.name = name; 14
this.length = name.length(); 15
} 16
17
public int getId() { 18
return id; 19
} 20
21
public String getName() { 22
return name; 23
} 24
25
public int getLength() { 26
return length; 27
} 28
29
public String toString() { 30
return id + "/" + name + ": " + length; 31
} 32
}
We'll be using this code to store and retrieve and instance of this class with different configuration settings:
01private static void tryStoreAndRetrieve(Configuration configuration) { 02
ObjectContainer container = Db4o.openFile(configuration, DB4O_FILE_NAME); 03
try { 04
NotStorable notStorable = new NotStorable(42, "Test"); 05
System.out.println("ORIGINAL: " + notStorable); 06
container.set(notStorable); 07
} catch (Exception exc) { 08
System.out.println(exc.toString()); 09
return; 10
} finally { 11
container.close(); 12
} 13
container = Db4o.openFile(DB4O_FILE_NAME); 14
try { 15
ObjectSet result = container.get(NotStorable.class); 16
while (result.hasNext()) { 17
NotStorable notStorable = (NotStorable) result.next(); 18
System.out.println("RETRIEVED: " + notStorable); 19
container.delete(notStorable); 20
} 21
} finally { 22
container.close(); 23
} 24
}
1private static void tryStoreWithoutCallConstructors() { 2
Configuration configuration = Db4o.newConfiguration(); 3
configuration.exceptionsOnNotStorable(false); 4
configuration.objectClass(NotStorable.class) 5
.callConstructor(false); 6
tryStoreAndRetrieve(configuration); 7
}
In this case our object seems to be nicely stored and retrieved, however, it has forgotten about its length, since db4o doesn't store transient members and the constructor code that sets it is not executed.
1private static void tryStoreWithCallConstructors() { 2
Configuration configuration = Db4o.newConfiguration(); 3
configuration.exceptionsOnNotStorable(true); 4
configuration.objectClass(NotStorable.class) 5
.callConstructor(true); 6
tryStoreAndRetrieve(configuration); 7
}
At storage time, db4o tests the only available constructor with null arguments and runs into a NullPointerException, so it refuses to accept our object.
(Note that this test only occurs when configured with exceptionsOnNotStorable - otherwise db4o will silently fail when trying to reinstantiate the object.)
This still does not work for our case because the native pointer will definetely be invalid.
In order to solve the problem we will need to use db4o Translators.