我在Payara Micro 5.2022.2应用程序中运行了以下JPQL查询。
TypedQuery<UserDto> query = entityManager.createQuery(
"SELECT new UserDto((FUNCTION('COALESCE', (select fullname from Person p where p.userId = u.id), 'Name not set'))) " +
" FROM User u WHERE u.id = :userId", User.class);
query.setParameter("userId", 12);
return query.getResultList();
字段的类型返回为java.lang.Object
,而不是java.lang.String
,因为列fullname
是其表中的varchar
。
这迫使我让构造函数具有Object
参数,而不是String
我想知道是否有办法让这个代码(FUNCTION('COALESCE', (select fullname from Person p where p.userId = u.id), 'Name not set')))
返回String
而不是Object
根据Andrey B.Panfilov的评论,我不得不将返回值强制转换为String:
TypedQuery<UserDto> query = entityManager.createQuery(
"SELECT new UserDto(CAST(FUNCTION('COALESCE', (select fullname from Person p where p.userId = u.id), 'Name not set') as text)) " +
" FROM User u WHERE u.id = :userId", User.class);
query.setParameter("userId", 12);
return query.getResultList();