Can I create static methods in @MappedSuperclasses?

I have an abstract TemporalModel class (annotated with @MappedSuperclass ) that adds the created and updated fields to all expanding models, I want to add the static getLatest() method to it:

 public static TemporalModel getLatest() { return find("order by created").first(); } 

When I put this method in a base class and call it through a specific class ( Transaction.getLatest() ), I get an error:

Unsupported Operation Exception: Please annotate your JPA model with @ javax.persistence.Entity annotation.

I suspect this is because the JPA does not really know that I am calling this method β€œthrough” the base class (in Java there is no real static method of inheritance).

Is there any other way to implement this method once, instead of repeating it on all entity classes?

Updating is one way to achieve this (which I use in another heavier application) is described here ( gist ). However, in my current application, I would not want to use repositories, and I wondered if there was an even easier solution.

+4
source share
2 answers

Constructors and static methods can never be abstract. The idea of ​​an abstract class is to create drawings of methods that need to be processed in subclass (s). I suggest trying the TemporalModel interface instead of the abstract class in which you create the public static TemporalModel getLatest () method;

+2
source

I have not used this Play platform, so I'm not sure about the details here, but usually when you do what you want to do in Java, you just specify a specific class as a parameter for the static method. Of course, this is ugly, but it is Java.

I assume that this find method is a static method that is somehow (via annotation processing) added to this structure on each expanding class, right? In this case, I think your only way out is to do something like this:

 public static <T extends TemporalModel> T getLatest(Class<T> cl) { try { /* I don't know what type the find() method returns, so you'll have to fix the casting */ return(cl.cast(cl.getMethod("find", String.class).invoke("order by created").first())); } catch(AllThosePeskyReflectionExceptions e) { throw(new Error(e)); } } 

I think the best way available in view of the premises. I know this is ugly, so I would be happy to be wrong. :)

+1
source

Source: https://habr.com/ru/post/1388631/


All Articles