使用休眠时空指针异常

时间:2013-05-06 10:44:05

标签: java spring hibernate postgresql nullpointerexception

我正在使用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类,我得到一个空指针异常。如何使hibernate忽略数据库中的空值并为bean类中的相应属性设置默认值。如你所见,我也使用了可空属性。它不起作用。

2 个答案:

答案 0 :(得分:2)

financialyearfromint,如果将列定义为可为空,则相应的列可能无法为null分配null值。

为了处理java原始变量中的空值,删除nullable=true并可能添加默认值0,因此db列中的所有空值都将转换为0或0.0等。

或者

使用包装类而不是Integer,这将允许您保留从db列分配的空值。

同样,以上两种方法通常适用于Hibernate实体中使用的原始变量。

进一步添加@ID列不应该是可以为空的IMO,如果它对应于主键列(在大多数情况下是这样),那么你的代码会出错,因为主键列不允许{ {1}}值。

答案 1 :(得分:0)

是否可以在查询中使用COALESCE为该字段分配默认值(如果为null)?如果有可能这可能是解决这个问题的最佳方法,而不必过多调整代码。

相关问题