Question

The goal

I've got a really strange problem. My goal is to compare a dynamic date in database using dbunit (the database is an Oracle one). This dynamic date is the today date (comparing static date works...)

The experimentation

To compare date, I use this very simple code :

@Test
public void simpleDateTest() throws DatabaseUnitException, SQLException {
    // create a date corresponding to today
    Date today = new Date();

    // load a dataset
    IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass()
            .getResource("/dataset.xml"));

    // replace [TODAY] by the today date
    ReplacementDataSet rDataSet = new ReplacementDataSet(expectedDataSet);
    rDataSet.addReplacementObject("[TODAY]", today);

    // insert the dataset
    DatabaseConnection connection = getConnection();
    DatabaseOperation.CLEAN_INSERT.execute(connection, rDataSet);

    // do a simple query to get some fields, em is the entity manager which uses the same connection as above
    Query q = em
            .createNativeQuery("SELECT ID, MY_DATE FROM MY_TABLE");
    List<Object[]> result = q.getResultList();

    // compare the date with today date
    assertEquals(today.getTime(), ((Date) result.get(0)[1]).getTime());
}

With the following dataset :

<?xml version='1.0' encoding='UTF-8'?>
<dataset>
    <MY_TABLE ID="1" MY_DATE="[TODAY]" />
</dataset>

The problem

I don't know why, but the assert failed ! When comparing the two dates, there is a very few milliseconds difference. The error is something like that :

java.lang.AssertionError: expected:<1358262234801> but was:<1358262234000>

I don't understand how is it possible to have different dates because they are quite normally the same ! Any clue to understand the problem and how to solve it ?

Was it helpful?

Solution

The Oracle Date type doesn't have a resolution of milliseconds, it only has a resolution of seconds.
When saving a time to the database the milliseconds are simply stripped off. When you look at the actual value you see that the last three digits are all zero.

OTHER TIPS

Assuming that today is a java.util.Date, the Java Date has millisecond precision. An Oracle date, on the other hand, does not have millisecond precision. So you would expect to lose some precision when you store a java.util.Date in Oracle and retrieve it back.

You could store the data in an Oracle timestamp column-- that will have millisecond precision. Or you could strip off the milliseconds from the Java Date before writing it to the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top