Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method in JPA

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;
    }
}
like image 389
Martynas Avatar asked Oct 20 '12 23:10

Martynas


People also ask

How do you call a function in hibernate?

You can call Hibernate's @NamedNativeQuery in the same way as you call any other named query. You only need to call the createNamedQuery of your EntityManager with the name of the query, set all bind parameter values and call the getSingleResult or getResultList method. TypedQuery<Review> q = em.

How does JPA handle null values?

The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.


2 Answers

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)

like image 169
DataNucleus Avatar answered Sep 28 '22 04:09

DataNucleus


Yes, you can! And no additional annotations are required.

ObjectDB is an implementation of an object-oriented database system (OODBS) and as a result allows you to interact with database items as objects, that includes calling methods, using inheritance and polymorphism, etc.

This is a simple working example I have. With a class like this:

@Entity
public class Person {
    private static final long serialVersionUID = 1L;

    @Id @GeneratedValue
    private long id;

    private String firstName;
    private String lastName;

    Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFullName() {
        return firstName + " " + lastName;
    }
}

This query returns correct results:

entityManager.createQuery(
    "SELECT p FROM Person p WHERE p.getFullName()='John Johnson'", Person.class).getResultList();
like image 37
Laurynas Lazauskas Avatar answered Sep 28 '22 02:09

Laurynas Lazauskas