I am trying to store timestamps into a db4o database, but the stored timestamps which store a few mninutes ago are much different from the current date.
Here are example outputs:
1969-12-31 19:00:00.741
1969-12-31 19:00:00.772
2012-10-14 00:23:22.713
The two previous stored timestamp was stored as 1969-12-31 19:00:00.7xx after I run my code three times.
Here is the code.
import java.sql.Timestamp;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
public class dbTest {
public static void listResults(ObjectSet<Timestamp> results) {
for (Timestamp o : results) {
System.out.println(o);
}
}
public static void main(String[] args) {
EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
config.common().objectClass(Timestamp.class).storeTransientFields(true);
ObjectContainer container = Db4oEmbedded
.openFile(config, "timestamps.db4o");
try {
long now = System.currentTimeMillis();
container.store(new Timestamp(now));
final ObjectSet<Timestamp> results = container.query(Timestamp.class);
listResults(results);
}
finally {
container.close();
}
}
}
I read the two pieces of related article below but the issue has not been solved.
Please advise me how to solve this issue. Thanks.
The solution to this problem by adding a line:
config.common().objectClass(Timestamp.class).translate(new TSerializable());
I got help from Vidisha & Claude at db4o forum. Here I share the answer, and hope to help other as well. Here is the new code.
import java.sql.Timestamp;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
public class dbTest {
public static void listResults(ObjectSet<Timestamp> results) {
for (Timestamp o : results) {
System.out.println(o);
}
}
public static void main(String[] args) {
EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
config.common().objectClass(Timestamp.class).translate(new TSerializable());
ObjectContainer container = Db4oEmbedded
.openFile(config, "timestamps.db4o");
try {
long now = System.currentTimeMillis();
container.store(new Timestamp(now));
final ObjectSet<Timestamp> results = container.query(Timestamp.class);
listResults(results);
}
finally {
container.close();
}
}
}
You are recommanded to use JDK Date which can be handled properly by db4o.