1

I'm working on an Android App that has it's own way to generate unique identifiers for entities.

Before every entity creation we assign a new ID for our objects. We're currently doing something like that:

IDGenerator.assignCodeFor(entity);
dao.create(entity);

I know that OrmLite has some sort of generateId id scheme, but seems like the feature were designed for working with database sequences(eg: PostgreSQL SERIAL datatype and mysql's AUTO_INCREMENT).

I already looked into customized DataPersister, but i came up with some sort of workarround that i don't feel confortable with.

TLDR;

So my question is: How can i programmatically generate custom ID for my entities with OrmLite?

I'm looking for something like a interceptor or a strategy pattern.

jairocgr
  • 11
  • 1

1 Answers1

0

How can i programmatically generate custom ID for my entities with OrmLite?

I think your example code is doing it, right? So really your question is:

How can I have ORMLite custom generate an ID for my entities.

The short answer is that it doesn't have a way to do this. ORMLite is not generating the ID, the database is. However, there are certainly ways that you can do this better in your own code.

  1. I'd extend the DAO and then override the dao.create(...) method so it assigns the ID for the entity and then calls super.create(...). The id field would obviously be @DatabaseField(id = true) and not generatedId = true.

  2. You could use a getId() and setId(...) method and use useGetSet = true on your entity field. Then inside of getId() in the entity, it would test if the id field were null and would do the generation of the id value at that moment. So then when ORMLite was interrogating the object to set the id field on the entity, it would be generated and then inserted into the database.

  3. You certainly could also just have a utility class and/or method which created the entities for you. That doesn't necessarily help unless you remember to use it all of the time of course.

  4. Could you do the id creation in the entity constructor? I suspect no but I thought I'd add it for consideration.

Gray
  • 115,027
  • 24
  • 293
  • 354