Enhancing our Entities
Let’s talk about Finder. It’s a feature from Ebean that allow us to enhance our entity with methods that will handle querying the database for that specific entity. With Kotlin, we can use it as a companion object to really make our life easier. Let me show you:
Now my Script entity will have methods like all(), query(), byId(), update() and many more. Take a look on the someExamples function on the Gist above, pretty easy right?
You could even create a ScriptFinder class extending Finder and create your own queries. In my case, I rather just use Finder as a companion object with it’s default methods and leave the custom queries to a service layer.
Back to our project
To illustrate these methods in use, I’m going to enhance our project entities and update our tests to reflect these changes. Here is our BaseEntitiesRelated.kt file now:
Notice that since I’m not using data classes (explained why 2 posts ago, I think) I also created a toString() method for all of them for our debugging later.
Now I’m going to update our old tests to reflect these changes. Please, keep in mind that it is still the very early stages of this project and you won’t see much use in all this. In fact, I just wanted to take this out of the way already because later we might even fully drop it from the project to favor a service layer instead.
This is the code for the updated test class:
And here is a diff between the two versions just to refresh your memory of for those who are just finding this project.
A bit easier, right?
See you on the next post!
Originally published at https://www.marcelustrojahn.com on September 14, 2019.