简体   繁体   中英

How can I effectively find a domain class instance based on ID if the domain class is unknown?

If I'm given an ID, but have no indication of which domain class it belongs to, how should I go about loading it?

I could test get() against each domain class in my app one at a time, but the code will be difficult to manage and rather inefficient. Is there an alternative method?

Yes, there is only one way: try to get() each domain, until you find one.

Btw, different domains can have exactly same id (depends on configuration).

As others have said, it's rather hard to do much with just an ID. The only real option you have is to try and retrieve each domain class with that ID, but as others mentioned as well, it's entirely possible that there may be more than one domain class that has an instance with that ID.

Thankfully, it's fairly easy to get a hold of all of the domain classes in your application and loop over them by using application.domainClasses .

Without knowing much about the context, it would be difficult more difficult to propose something. If you have access to the instance that returned id, then maybe you can find out the class and then use that class to do a get().

You can add some sort of "metadata" to your id.

For example, lets say you have 2 Domain classes: Book and Author. In database you crate two sequence of ids for that tables, one in range 100000 - 199999 and second in range of 200000-299999.

Now, when you have an Id you can check it for ranges and find out which domain object it is. It will be faster then going through all domain classes and calling get() on them, especially if you got some eager-loading collections.

But cons is that you have to manage this ranges somehow and always remember about them and be sure to cover situation where sequence runs out of free ids.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM