Question

Is there any way not to describe every model in Play? When using Ebean I wind up writing the definition of the Finder in every model:

public static Finder<Long,Task> find = new Finder<Long,Task>(
    Long.class, Task.class
  );

also I usually declare the methods all, create, delete, update and a couple more, according to the circumstances.

public static List<Task> all() {
    return Task.find.all();
}

public static void create(Task task) {
    task.save();
}
...

I was wondering if it is possible to define all this stuff just once and then if a model needs some different functionality just re-declare it just for the model that needs it. I tried to declare a parent class for the models using generics CustomModel, and apparently java doesn't like generic methods to be static which is understandable. So is this even possible? I did that in PHP a while ago.

I'm new to Play and Java in general and I would be very thankful if anyone could help me with that.

Thank you guys!

Was it helpful?

Solution

Because of the type erasure in Java, Finder will loose Long and Task during compilation and not know about them during runtime which makes it really hard to make such an abstraction.

There is no problem using generics with statics in Java but you have to understand what scope you are in. A static method cannot access parameterized types from the class it is defined in since that would require an actual instance of the class.

One idea could be to create a non-static helper class that only takes one type parameter (the entity type) and the .class of it to its constructor and creates the finder and can have methods that implement common operations. Then create a static instance of that inside all your entities.

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