我在任何地方都找不到类似的问题,也没有类似的答案,经过数小时的搜索,我终于找到了解决方法。
问题:
在Java本机查询中使用UNION并具有列的值,该值始终为空字符串(''
)
(一个简单的虚拟示例) 查询字符串
String queryString = "SELECT * FROM ( " +
" SELECT " +
" a_type as 'Contract Type', " +
" name as 'Full Name', " +
" lent_value as 'Credits', " +
" '' as 'Payment Info' " +
" FROM free_users " +
" UNION " +
" SELECT " +
" type as 'Contract Type', " +
" name as 'Full Name', " +
" value as 'Credits', " +
" payment_info as 'Payment Info' " +
" FROM paid_users " +
") results " +
"ORDER BY results.`Full Name` ";
使用实体管理器创建查询
Query query = entityManager.createNativeQuery(queryString);
并执行它
query.getResultList();
在StringIndexOutOfBoundsException
中返回的错误消息为错误消息String index out of range: 0
发生此问题是由于 first SELECT中具有空字符串列。
休眠状态与 first SELECT的''
值不匹配,因此以下UNION失败。
该列的值必须至少为 ,且字符串长度为1个字符
更正的查询字符串
String correctedQueryString = "SELECT * FROM ( " +
" SELECT " +
" a_type as 'Contract Type', " +
" name as 'Full Name', " +
" lent_value as 'Credits', " +
" 'p' as 'Payment Info' " +
" FROM free_users " +
" UNION " +
" SELECT " +
" type as 'Contract Type', " +
" name as 'Full Name', " +
" value as 'Credits', " +
" payment_info as 'Payment Info' " +
" FROM paid_users " +
") results " +
"ORDER BY results.`Full Name` ";