Search code examples
javajpapersistenceeclipselink

Persisting with @Transient


In my POJO I have this:

@Transient
private int qtyMentee;

and in my DAO I have this query:

public List<Employee> findQtyMentee(){
    TypedQuery<Employee> query = (TypedQuery<Employee>) em.createNativeQuery(
        "select *, count(mentor_id) as qtymentee from employee group by id order by qtymentee asc" , Employee.class);
    Collection<Employee> employee  = (Collection<Employee>) query.getResultList();
    return (List<Employee>) employee;
}

When I try to get Qtymentee ever returns 0.

The annotation @Transient is wrong in this situation?

How can I get this value and show in my application?

OBS: I'm using Eclipselink.

Thanks.


Solution

  • What you are trying to do is not supported. Transient means it is not a field that is mapped or handled by JPA in anyway - it is excluded from being read or persisted from the database. In this case, you are trying to push calculated data into the entity field, which would corrupt your cache of entities maintained by the context.

    Hopefully you have mapped this as a 1:M (Say employee.mentees) and M:1 (say employee.mentor) in your object model. If so, a simple size on the collection mapping will return the number of "mentee"s without the need of storing the value somewhere.

    If you want the list ordered with the value returned directly, using JPQL (instead of SQL with the createNativeQuery method):

    List<Object[]> list = createQuery("Select e, size(e.mentees) as qtymentee from Employee e order by qtymentee asc").getResultList();
    

    If you haven't mapped the mentor_id field using reference mappings, you would need to resort to using a subqueries as I don't believe your SQL query posted would work.

    If you must put it into a data object, you can use a constructor expression described here http://docs.oracle.com/cd/E15523_01/apirefs.1111/e13946/ejb3_langref.html#ejb3_langref_constructor

    It would look something like:

      createQuery("select new DAO(e.id, e.otherfield .., size(e.mentees)) from Employee e")