Why do I get a “Null value was assigned to a prope

2019-03-09 15:04发布

I get the following error when using a primitive attribute in my grails domain object:

Null value was assigned to a property of primitive type setter of MyDomain.myAttribute
 org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of MyDomain.myAttribute
at grails.orm.HibernateCriteriaBuilder.invokeMethod(HibernateCriteriaBuilder.java:1077)

标签: grails gorm
10条回答
一纸荒年 Trace。
2楼-- · 2019-03-09 15:11

According to this SO thread, the solution is to use the non-primitive wrapper types; e.g., Integer instead of int.

查看更多
何必那么认真
3楼-- · 2019-03-09 15:12

There are two way

  • Make sure that db column is not allowed null
  • User Wrapper classes for the primitive type variable like private int var; can be initialized as private Integer var;
查看更多
聊天终结者
4楼-- · 2019-03-09 15:13

A null value cannot be assigned to a primitive type, like int, long, boolean, etc. If the database column that corresponds to the field in your object can be null, then your field should be a wrapper class, like Integer, Long, Boolean, etc.

The danger is that your code will run fine if there are no nulls in the DB, but will fail once nulls are inserted.

And you can always return the primitive type from the getter. Ex:

  private Integer num;

  public void setNum(Integer i) {
    this.num = i;
  }

  public int getNum() {
    return this.num;
  }

But in most cases you will want to return the wrapper class.

So either set your DB column to not allow nulls, or use a wrapper class.

查看更多
小情绪 Triste *
5楼-- · 2019-03-09 15:13

Change the parameter type from primitive to Object and put a null check in the setter. See example below

public void setPhoneNumber(Long phoneNumber) {
    if (phoneNumber != null)
        this.phoneNumber = phoneNumber;
    else
        this.extension = 0l;
}
查看更多
神经病院院长
6楼-- · 2019-03-09 15:16

Make sure your database myAttribute field contains null instead of zero.

查看更多
一夜七次
7楼-- · 2019-03-09 15:21

Either fully avoid null in DB via NOT NULL and in Hibernate entity via @Column(nullable = false) accordingly or use Long wrapper instead of you long primitives.

A primitive is not an Object, therefore u can't assign null to it.

查看更多
登录 后发表回答