The following example shows a cross-platform system where classes were saved to the
db4o database from a .NET application and read and modified later from a
.Java application. A vice versa example is reviewed in
Cross-Platform Aliasing.
Pilot objects are saved to a database from a .NET application:
01private static void SaveObjects() 02
{ 03
File.Delete(Db4oFileName); 04
IObjectContainer container = Db4oFactory.OpenFile(Db4oFileName); 05
try 06
{ 07
Pilot pilot = new Pilot("David Barrichello", 99); 08
container.Set(pilot); 09
pilot = new Pilot("Michael Schumacher", 100); 10
container.Set(pilot); 11
} 12
finally 13
{ 14
container.Close(); 15
} 16
}
01Private Shared Sub SaveObjects() 02
File.Delete(Db4oFileName) 03
Dim container As IObjectContainer = Db4oFactory.OpenFile(Db4oFileName) 04
Try 05
Dim pilot As New Pilot("David Barrichello", 99) 06
container.[Set](pilot) 07
pilot = New Pilot("Michael Schumacher", 100) 08
container.[Set](pilot) 09
Finally 10
container.Close() 11
End Try 12
End Sub
In order to read the saved objects successfully from a java application we will need to define an alias for persistent classes and an alias for the Db4oDatabase class. We will use a wildcard alias for all the persistent classes:
01private static Configuration configureAlias() { 02
Configuration configuration = Db4o.newConfiguration(); 03
configuration.addAlias(new WildcardAlias( 04
"Db4objects.Db4odoc.Aliases.*, Db4objects.Db4odoc", 05
"com.db4odoc.aliases.*")); 06
configuration.addAlias(new TypeAlias( 07
"Db4objects.Db4o.Ext.Db4oDatabase, Db4objects.Db4o", 08
"com.db4o.ext.Db4oDatabase")); 09
return configuration; 10
}
01private static void getObjects(Configuration configuration) { 02
ObjectContainer db = Db4o.openFile(configuration, DB4O_FILE_NAME); 03
try { 04
List<Pilot> result = db.query(new Predicate<Pilot>() { 05
public boolean match(Pilot pilot) { 06
return true; 07
} 08
}); 09
for (int i = 0; i < result.size(); i++) { 10
Pilot pilot = result.get(i); 11
pilot.setName("Modified " + pilot.getName()); 12
db.set(pilot); 13
} 14
listResult(result); 15
} finally { 16
db.close(); 17
} 18
}
One thing to remember: field names in class definitions in Java and .NET should be exactly the same.
We can read the database from the initial .NET application again. Note, that no alias is required as the class definitions were created in this application :
01private static void ReadObjects() 02
{ 03
IObjectContainer container = Db4oFactory.OpenFile(Db4oFileName); 04
try 05
{ 06
IList<Pilot> result = container.Query<Pilot>(); 07
ListResult(result); 08
} 09
finally 10
{ 11
container.Close(); 12
} 13
}
1Private Shared Sub ReadObjects() 2
Dim container As IObjectContainer = Db4oFactory.OpenFile(Db4oFileName) 3
Try 4
Dim result As IList(Of Pilot) = container.Query(Of Pilot)() 5
ListResult(result) 6
Finally 7
container.Close() 8
End Try 9
End Sub