Call method in JPA

Martynas picture Martynas · Oct 21, 2012 · Viewed 10.5k times · Source

I'm using ObjectDB with JPA. I would like to call myMethod(). For example:

entityManager.createQuery("SELECT ... FROM ... WHERE MyClass.myMethod() = 100")

Is it possible? Maybe any annotation is required before method in the class?

@Entity
public class MyClass implements Serializable {

    @Basic 
    private int x;

    @Basic
    private int y;

    public int myMethod() {
        return x*1000+y;
    }
}

Answer

DataNucleus picture DataNucleus · Oct 21, 2012

JPQL is not exactly an object-based query language. You can't define your own methods, and JPQL provides a very limited set of functions. So if you want to keep within the JPA spec then the answer is no; would have to be JPA-implementation specific - DataNucleus JPA certainly allows you to have your own methods in the query language (as a vendor extension), no idea about your quoted JPA provider - that said though, it would only execute such a query in the datastore if you put the code for that method in a query method implementation (as opposed to in the class)