Java Translator Implementation

This topic applies to Java version only

To translate NotStorable instances, we will pack their id and name values into an Object array to be stored and retrieve it from there again. Note that we don't have to do any work in onActivate(), since object reinstantiation is already fully completed in onInstantiate().

NotStorableTranslator.java
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02package com.db4odoc.translators; 03 04import com.db4o.*; 05import com.db4o.config.*; 06 07public class NotStorableTranslator implements ObjectConstructor { 08 public Object onStore(ObjectContainer container, 09 Object applicationObject) { 10 System.out.println("onStore for " + applicationObject); 11 NotStorable notStorable = (NotStorable) applicationObject; 12 return new Object[] { new Integer(notStorable.getId()), 13 notStorable.getName() }; 14 } 15 16 public Object onInstantiate(ObjectContainer container, 17 Object storedObject) { 18 System.out.println("onInstantiate for " + storedObject); 19 Object[] raw = (Object[]) storedObject; 20 int id = ((Integer) raw[0]).intValue(); 21 String name = (String) raw[1]; 22 return new NotStorable(id, name); 23 } 24 25 public void onActivate(ObjectContainer container, 26 Object applicationObject, Object storedObject) { 27 System.out.println("onActivate for " + applicationObject 28 + " / " + storedObject); 29 } 30 31 public Class storedClass() { 32 return Object[].class; 33 } 34}

Let's try it out:

TranslatorExample.java: storeWithTranslator
1private static void storeWithTranslator() { 2 Configuration configuration = Db4o.newConfiguration(); 3 configuration.objectClass(NotStorable.class).translate( 4 new NotStorableTranslator()); 5 tryStoreAndRetrieve(configuration); 6 }