Search code examples
javahibernatespring-boothibernate-criteria

How to accept Tuple of type Map<String,Object> in JPA


Currently Hibernate tuple accept Map<String,String> return type but i need return type of Map<String,Object> how to achieve this.

Example:

class User {
  long id;
  String imageUrl;
  Address address;

 String username;

 String password;

  String email;

}

class Address {
long id;
String name;
String Street code;
}

My Criteria Query:

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = builder.createTupleQuery();
    Root<User> root = cq.from(User.class);
    cq.multiselect(
        root.get("imageUrl"),
        root.get("address"));
    cq.where(builder.equal(root.get("id"),3));
    Tuple tuple = entityManager.createQuery(cq).getSingleResult();
    tuple.get(0);
// Error occurs for below code. (Stack over flow exception)
    tuple.get(1);

While getting imageUrl there is no error but when it tries to fetch address [Address type not string] attribute hibernate triggers stack over flow exception because it was trying to convert address to string.

Is there any other approach to achieve this.. ?


Solution

  • The issue is with toString() which the address to String.

    Where the toString() method in Address class tries to print User object recursively.

    That is the reason for stackoverflow.