Storing Timestamp And Date Values

This topic applies to Java version only 

Problem

If you've been working with java.sql.Date, java.sql.Timestamp or other classes extending java.util.Date, you should know that they cannot be stored to db4o by default. To see the problem try to run the following methods, using the default configuration:

Configuration configuration = Db4o.newConfiguration();

TimestampExample.java: storeTimestamp
01private static void storeTimestamp(Configuration configuration) { 02 new File(DB4O_FILE_NAME).delete(); 03 04 ObjectContainer container = database(configuration); 05 if (container != null) { 06 try { 07 Timestamp timestamp = new Timestamp(System.currentTimeMillis()); 08 System.out.println("timestamp: " + timestamp); 09 10 container.set(timestamp); 11 12 container.commit(); 13 } catch (Exception ex) { 14 System.out.println("Exception: " + ex.toString()); 15 } finally { 16 closeDatabase(); 17 } 18 } 19 }
TimestampExample.java: retrieveTimestamp
01private static void retrieveTimestamp(Configuration configuration) { 02 ObjectContainer container = database(configuration); 03 if (container != null) { 04 try { 05 ObjectSet result = container.query(Timestamp.class); 06 listResult(result); 07 08 } catch (Exception ex) { 09 System.out.println("Exception: " + ex.toString()); 10 } finally { 11 closeDatabase(); 12 } 13 } 14 }

Reason

java.sql.Date or java.sql.Timestamp classes extend java.util.Date class, which has a transient field, preventing it from being stored. (Note, that using java.util.Date as a field in your class does not raise any problem, as this class gets special treatment by db4o.)

Solution

The problem can be solved by applying the following configuration to the object container:

TimestampExample.java: configure
1private static Configuration configure() { 2 Configuration configuration = Db4o.newConfiguration(); 3 configuration.objectClass(Date.class).storeTransientFields(true); 4 return configuration; 5 }

Try to run storeTimestamp and retrieveTimestamp methods using the new configuration.

The same solution can be applied to java.sql.Date and java.util.Date classes.