javagenericsdaoormlite

In ORMLite why should we use DAOs with an ID of a specific type when Object seems to work?


I can extend BaseDaoImpl using either Dao<InvoiceItem, Object> or Dao<InvoiceItem, UUID>, for instance. Why would I specify UUID when Object seems to work just as well?

Using Object in all of my Dao implementations in a large-ish project have been working so far. I thought I may have tripped over a case where it was breaking object cache functionality after enabling it, but my testing of the pattern used in ORMLite's ReferenceObjectCache.java to store and retrieve references from a Map showed that it works fine with either strongly typed keys or keys cast as Object.

I still haven't figured out why the object cache feature is not working for me after enabling it (same data, different objects), but trying to figure this out has me wondering why there is even a reason to specify the ID type in a ORMLite DAO to begin with.


Solution

  • I can extend BaseDaoImpl using either Dao<InvoiceItem, Object> or Dao<InvoiceItem, UUID>, for instance. Why would I specify UUID when Object seems to work just as well?

    Dao is a generic class. Your question would be similar when you are talking about List<UUID> compared to List<Object>. The generic types mean that when you call dao.deleteById(uuid) it would provide type checking to validate that the id was the correct class. If you were using an Object id, you could inappropriately call dao.deleteById("hello") which would not find your object if the ID field was a UUID.

    Also, if you call UUID id = dao.extractId(data), you don't have to cast the result because the compiler knows that the method returns a UUID.

    Using Object in all of my Dao implementations in a large-ish project have been working so far.

    The generic types are really only for the caller and provides compiler time type checking. Under the covers the ID type in the BaseDaoImpl is just an object.

    Here's the tutorial from Oracle on why we use generics that might help your understanding. Their top reasons are: