簡體   English   中英

使用休眠時空指針異常

[英]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屬性。 它不起作用。

financialyearfromint ,雖然列被定義為可為空,但是對應的列在數據庫中可能具有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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM