简体   繁体   中英

Null pointer exception while using hibernate

I am using Hibernate and spring. this is my model class

@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;
    }

I am using Hibernate to call a stored procedure in postgres database. The stored procedure returns a table which is mapped to this model class. Now my problem is, the table that is returned from the database contains a null value. I am in the need of doing some manipulations on the data. Now since the null value is mapped to the bean class I am getting a null pointer exception. How can I make hibernate ignore the null values in the database and set a default value for the corresponding property in the bean class. As you can see I have used nullable property also. It does'nt work.

financialyearfrom is int which cannot be assigned null value though corresponding column you might be having null value in database if column is defined as nullable.

For handling null values in java primitive variables, remove nullable=true and possible add default value 0, so all null value from db column would convert to 0 or 0.0 etc.

Or

Use wrapper class instead ie Integer which will allow you to retain null value assigned from db column.

Again, above two approaches are in general applicable for primitive variables using in Hibernate entities.

Further to add @ID column shouldn't be nullable IMO, if it corresponds to primary key column (in most of the cases it is) so your code would be wrong as primary key column doesn't allow null values.

Would it be possible to use COALESCE in your query to assign a default value to that field if its null? If that's possible that's probably the best way to fix this issue w/o having to tweak your code too much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM