简体   繁体   English

如何防止仅包含String构造函数的JPA查询,当仅提供null字符串值时抛出NullPointerException

[英]How to prevent JPA query including a String constructor, throwing a NullPointerException when a null String value is only availabe

I have the following JPA query: select NEW java.lang.String(c.country) from Contact c group by c.country order by c.country 我有以下JPA查询:按c.country从Contact c组中选择NEW java.lang.String(c.country)

When one of the rows in Contact table holds null value for country field, the String constructor in the JPA query above throws a NullPointerException. 当Contact表中的某一行的国家/地区字段为空值时,上述JPA查询中的String构造函数将引发NullPointerException。

As a null value in the country field in Contact table is allowed, is there any way to prevent it via code and still use a named query? 由于允许在联系人表的国家/地区字段中使用空值,是否有任何方法可以通过代码阻止它并仍使用命名查询?

关于什么

select c.country from Contact c where c.country is not null group by c.country order by c.country

A group by makes no sense here, since you don't have any aggregate function in the select clause. 这里的group by没有意义,因为select子句中没有任何聚合函数。 Calling the string constructor is also useless. 调用字符串构造函数也是没有用的。

Just use 只需使用

select c.country from Contact c order by c.country

If the goal of the group by is to select distinct values, use distinct : 如果分组依据的目标是选择不同的值,请使用distinct

select distinct c.country from Contact c order by c.country

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM