我正在使用 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 数据库中的存储过程。存储过程返回一个映射到该模型类的表。现在我的问题是,从数据库返回的表包含一个空值。我需要对数据进行一些操作。现在,由于空值被映射到 bean 类,我得到了一个空指针异常。如何让hibernate忽略数据库中的空值并为bean类中的相应属性设置默认值。如您所见,我也使用了可空属性。它不起作用。
最佳答案
financialyearfrom
是 int
无法分配 null
值,尽管相应的列中可能有 null
值数据库,如果列被定义为可为空。
为了处理 java 原始变量中的空值,删除 nullable=true
并可能添加默认值 0,这样来自 db 列的所有空值都会转换为 0 或 0.0 等。
或者
改用包装类,即 Integer
,这将允许您保留从 db 列分配的空值。
同样,上述两种方法通常适用于 Hibernate
实体中使用的原始变量。
进一步添加 @ID
列不应该是可为空的 IMO,如果它对应于主键列(在大多数情况下是),那么您的代码将是错误的,因为主键列不不允许 null
值。
关于java - 使用hibernate时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16397052/