JPQL: How to "select a new Foo (null, null ... someValue, ..)?

For example, I have an entity

public class Foo { private String col1; private String col2; private String col3; private String col4; //getters and setters } 

I want to do select only col3 and col4 . But I already have a Foo constructor, as shown below:

 public Foo (String col1, String col2) { this.col1 = col1; this.col2 = col2; } 

Thus, I cannot have another constructor for col3 and col4 , because it will have the same signature.

What I'm trying to do so far is to create a complete constructor, for example:

 public Foo (String col1, String col2, String col3, String col4) { this.col1 = col1; this.col2 = col2; this.col3 = col3; this.col4 = col4; } 

But when I try to do something like below in my request

 SELECT new Foo(null, null, f.col3, f.col4) FROM Foo f 

I get

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected end of subtree

Although trying

 SELECT new Foo(f.col1, f.col2, f.col3, f.col4) FROM Foo f 

It works as expected.

EDIT:

I tried

 Select f.col3, col4.. 

and the error below has been reset

 org.springframework.dao.InvalidDataAccessApiUsageException: Cannot create TypedQuery for query with more than one return using requested result type [com.lala.entity.Foo]; nested exception is java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [com.lala.entity.Foo] 
+4
source share
2 answers

You can try (but just try)

 SELECT new Foo(cast(null as string), cast(null as string), f.col3, f.col4) FROM Foo f 

or look at cast () operator for JPQL if supported (I'm not sure)
yet

 Session session = entityManager.unwrap(Session.class); List<Foo> list = session.createQuery("select f.col3, f.col4 from Foo f").list() 

This is a Hibernate specification, and for each forecast you do not need a specific constructor; just create an empty Foo() constructor Foo() at least protected, I don’t remember if private is allowed) and let Hibernate insert the value in col3, col4 from your query (and the cast() statement is supported if your base database supports this function )

+5
source

I know this question is old, but you can also do it (if the cast didn’t work for you):

 String query = "select new Pojo( " + " trim(:null), " + " trim(:null), " + " f.col3, " + " f.col4 " + " ) " + " from Foo as f "; return em.createQuery(query, Pojo.class) .setParameter("null", null) .getResultList(); 

Edited: JPA ignores literal columns when matching them with constructor arguments, so it is wrapped with cropping so that the JPA knows about the literal value.

+2
source

Source: https://habr.com/ru/post/1499059/


All Articles