[英]Null pointer exception while using hibernate
我正在使用Hibernate和spring。 这是我的模特班
@Entity
@NamedNativeQueries({@NamedNativeQuery(
name = "CSI_TARGET",
query = "select * from CSITARGET('CSIINDEX',2)",
resultClass = CSITarget.class)})
public class CSITarget {
@Column(name="csi_target")
private BigDecimal csi_target;
@Id
@Column(name="financialyearfrom" ,nullable = true)
private int financialyearfrom =0;
@Column( name="at_yearhalf" , nullable = true)
private String at_yearhalf = "";
public BigDecimal getCsi_target() {
return csi_target;
}
public void setCsi_target(BigDecimal csi_target) {
this.csi_target = csi_target;
}
public int getFinancialyearfrom() {
return financialyearfrom;
}
public void setFinancialyearfrom(int financialyearfrom) {
this.financialyearfrom = financialyearfrom;
}
public String getAt_yearhalf() {
return at_yearhalf;
}
public void setAt_yearhalf(String at_yearhalf) {
this.at_yearhalf = at_yearhalf;
}
我正在使用Hibernate在postgres数据库中调用存储过程。 该存储过程返回一个映射到该模型类的表。 现在我的问题是,从数据库返回的表包含一个空值。 我需要对数据进行一些操作。 现在,由于null值已映射到Bean类,因此我得到了null指针异常。 如何使休眠状态忽略数据库中的空值,并为Bean类中的相应属性设置默认值。 如您所见,我也使用了nullable属性。 它不起作用。
financialyearfrom
是int
,虽然列被定义为可为空,但是对应的列在数据库中可能具有null
值,因此无法将其分配为null
值。
为了在Java基本变量中处理null值,请删除nullable=true
并可能添加默认值0,因此db列中的所有null值都将转换为0或0.0等。
要么
请使用包装器类,即Integer
,它可以让您保留从db列分配的空值。
同样,以上两种方法通常适用于在Hibernate
实体中使用的原始变量。
此外,如果@ID
列与主键列相对应(在大多数情况下是),则@ID
列不应为可空值,因此您的代码将是错误的,因为主键列不允许使用null
值。
如果查询的字段为null,是否可以在查询中使用COALESCE为其指定默认值? 如果可能的话,这可能是解决此问题的最佳方法,而无需过多地调整代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.