Search code examples
javahibernatejpaplayframeworkplayframework-1.x

JPA persistence and Hibernate javassist objects


I am using Play Framework v.1.2.6 for a project and I have issues with hibernation of objects when i am trying to retrieve them from database. https://www.playframework.com/documentation/1.2.x/jpa

I have a query which selects rows from a mysql table and in the result there are proxy objects. Please see image below.enter image description here

I am not using any Hibernate configuration file. I am using only @Annotations in my model class.

Example of my query:

static List<User> getAllUsersFromAccount(Account account) {
    return  User.find(
            "SELECT u " +
            "FROM User u " +
            "WHERE u.account=?", 
            account).fetch();
}

Does anyone knows how can i avoid getting proxy objects in the query results?

For now we iterate over the array of users and check if the entity is instanceof HibernateProxy. We do not want to do that because maybe we have the same problem and for other queries.

private static <T> T initializeAndUnproxy(T entity) {
    Hibernate.initialize(entity);
    if(entity instanceof HibernateProxy) {
        entity = (T)((HibernateProxy)entity).getHibernateLazyInitializer().getImplementation();
    }
    return entity;
}

Solution

  • You can use JOIN FETCH keyword in you JPQL/HQL query. In you example, if you don't want to deal with proxy objects instead of real Account objects add 'JOIN FETCH u.account'

    static List<User> getAllUsersFromAccount(Account account) {
        return  User.find(
                "SELECT u " +
                "FROM User u " +
                "JOIN FETCH u.account " +
                "WHERE u.account=?", 
                account).fetch();
    }