TSerializable translator allows persistence of classes that do not have a constructor acceptable for db4o (For more information see Translators). Under the hood this translator converts an object to a memory stream on store and restores it upon instantiation. The limitations of this translator:
TSerializable translator should be used only with classes implementing java.io.Serializable interface (Java) or using [Serializable] attribute (.NET).
01/* Copyright (C) 2007 db4objects Inc. http://www.db4o.com */ 02
03
package com.db4odoc.builtintranslators; 04
05
import java.io.Serializable; 06
07
public class Pilot implements Serializable { 08
public String _name; 09
10
public int _points; 11
12
public Pilot() { 13
} 14
15
public Pilot(String name, int points) { 16
_name = name; 17
_points = points; 18
} 19
20
public String getName() { 21
return _name; 22
} 23
24
public void setName(String name) { 25
_name = name; 26
} 27
28
public int getPoints() { 29
return _points; 30
} 31
32
public String toString() { 33
return _name + "/" + _points; 34
} 35
36
}
01public static void saveSerializable() 02
{ 03
new File(DB4O_FILE_NAME).delete(); 04
Configuration configuration = Db4o.newConfiguration(); 05
// configure class as serializable 06
configuration.objectClass(Pilot.class).translate(new TSerializable()); 07
ObjectContainer container = database(configuration); 08
if (container != null) 09
{ 10
try 11
{ 12
Pilot pilot = new Pilot("Test Pilot 1", 99); 13
container.set(pilot); 14
pilot = new Pilot("Test Pilot 2", 100); 15
container.set(pilot); 16
} 17
catch (Db4oException ex) 18
{ 19
ex.printStackTrace(); 20
} 21
catch (Exception ex) 22
{ 23
ex.printStackTrace(); 24
} 25
finally 26
{ 27
closeDatabase(); 28
} 29
} 30
31
}
01public static void testSerializable() 02
{ 03
saveSerializable(); 04
Configuration configuration = Db4o.newConfiguration(); 05
// configure class as serializable to retrieve correctly 06
configuration.objectClass(Pilot.class).translate(new TSerializable()); 07
ObjectContainer container = database(configuration); 08
if (container != null) 09
{ 10
try 11
{ 12
System.out.println("Retrieving pilots by name:"); 13
Query query = container.query(); 14
query.constrain(Pilot.class); 15
query.descend("_name").constrain("Test Pilot 1"); 16
ObjectSet resultByName = query.execute(); 17
listResult(resultByName); 18
19
System.out.println("Retrieve all pilot objects:"); 20
ObjectSet result = container.query(Pilot.class); 21
listResult(result); 22
} 23
catch (Db4oException ex) 24
{ 25
ex.printStackTrace(); 26
} 27
catch (Exception ex) 28
{ 29
ex.printStackTrace(); 30
} 31
finally 32
{ 33
closeDatabase(); 34
} 35
} 36
}