Why do I get a “Null value was assigned to a property of primitive type setter of” error message when using HibernateCriteriaBuilder in Grails

后端 未结 12 669
长情又很酷
长情又很酷 2021-01-30 07:58

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         


        
12条回答
  •  北海茫月
    2021-01-30 08:20

    I'll try to make you understand with the help of an example. Suppose you had a relational table (STUDENT) with two columns and ID(int) and NAME(String). Now as ORM you would've made an entity class somewhat like as follows:-

    package com.kashyap.default;
    
    import java.io.Serializable;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    /**
     * @author vaibhav.kashyap
     *
     */
    @Entity
    @Table(name = "STUDENT")
    public class Student implements Serializable {
    
        /**
         * 
         */
        private static final long serialVersionUID = -1354919370115428781L;
    
        @Id
        @Column(name = "ID")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
    
        @Column(name = "NAME")
        private String name;
    
        public Student(){
    
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    

    Lets assume table already had entries. Now if somebody asks you add another column of "AGE" (int)

    ALTER TABLE STUDENT ADD AGE int NULL

    You'll have to set default values as NULL to add another column in a pre-filled table. This makes you add another field in the class. Now the question arises whether you'll be using a primitive data type or non primitive wrapper data type for declaring the field.

    @Column(name = "AGE")
    private int age;
    

    or

    @Column(name = "AGE")
    private INTEGER age;
    

    you'll have to declare the field as non primitive wrapper data type because the container will try to map the table with the entity. Hence it wouldn't able to map NULL values (default) if you won't declare field as wrapper & would eventually throw "Null value was assigned to a property of primitive type setter" Exception.

提交回复
热议问题