有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用hibernate时出现java空指针异常

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


共 (2) 个答案

  1. # 1 楼答案

    financialyearfromint不能赋值的null值,但对应的列如果列定义为可空,则数据库中可能有null

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

    或者

    改为使用包装类,即Integer,这将允许您保留从db列分配的空值

    同样,上述两种方法通常适用于使用Hibernate实体的基本变量

    此外,如果@ID列对应于主键列(在大多数情况下是这样),那么它在IMO中不应为空,因此您的代码将是错误的,因为主键列不允许null

  2. # 2 楼答案

    如果字段为空,是否可以在查询中使用COALESCE为该字段指定默认值?如果可能的话,这可能是解决这个问题的最好方法,而不必对代码进行太多调整