Grails에서 HibernateCriteriaBuilder를 사용할 때 "Null 값이 기본 유형 setter의 속성에 할당되었습니다"라는 오류 메시지가 나타나는 이유는 무엇입니까?
내 grails 도메인 개체에서 기본 속성을 사용할 때 다음 오류가 발생합니다.
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)
이 SO 스레드 에 따르면 해결책은 기본이 아닌 래퍼 유형을 사용하는 것입니다. 예 : Integer
대신 int
.
null 값은 int, long, boolean 등과 같은 기본 유형에 할당 할 수 없습니다. 개체의 필드에 해당하는 데이터베이스 열이 null 일 수있는 경우 필드는 Integer, Long,과 같은 래퍼 클래스 여야합니다. 부울 등
위험은 DB에 null이 없으면 코드가 제대로 실행되지만 null이 삽입되면 실패한다는 것입니다.
그리고 항상 getter에서 기본 유형을 반환 할 수 있습니다. 전의:
private Integer num;
public void setNum(Integer i) {
this.num = i;
}
public int getNum() {
return this.num;
}
그러나 대부분의 경우 래퍼 클래스를 반환하고 싶을 것입니다.
따라서 DB 열을 null을 허용하지 않도록 설정하거나 래퍼 클래스를 사용하십시오.
기본 유형은 널일 수 없습니다. 따라서 해결책은 tableName.java 파일에서 기본 유형을 기본 래퍼 클래스로 바꾸는 것입니다. 예 :
@Column(nullable=true, name="client_os_id")
private Integer client_os_id;
public int getClient_os_id() {
return client_os_id;
}
public void setClient_os_id(int clientOsId) {
client_os_id = clientOsId;
}
원시 유형의 래퍼 클래스를 찾으려면 http://en.wikipedia.org/wiki/Primitive_wrapper_class 를 참조 하십시오 .
예를 들어 이해하도록 노력하겠습니다. 두 개의 열과 ID (int) 및 NAME (String)이있는 관계형 테이블 (STUDENT)이 있다고 가정하십시오. 이제 ORM으로 다음과 같은 엔티티 클래스를 만들었습니다.
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;
}
}
테이블에 이미 항목이 있다고 가정합니다. 이제 누군가 "AGE"(int)의 다른 열을 추가하라고 요청하면
ALTER TABLE 학생 추가 연령 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.
use Integer as the type and provide setter/getter accordingly..
private Integer num;
public Integer getNum()...
public void setNum(Integer num)...
@Dinh Nhat, your setter method looks wrong because you put a primitive type there again and it should be:
public void setClient_os_id(Integer clientOsId) {
client_os_id = clientOsId;
}
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.
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;
}
Make sure your database myAttribute field contains null instead of zero.
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 asprivate Integer var;
Do not use primitives in your Entity classes, use instead their respective wrappers. That will fix this problem.
Out of your Entity classes you can use the != null validation for the rest of your code flow.
'development' 카테고리의 다른 글
ComboBox- SelectionChanged 이벤트에 새 값이 아닌 이전 값이 있습니다. (0) | 2020.09.20 |
---|---|
사람이 읽을 수있는 형식으로 다중 레벨 배열을 (로그에) 출력하는 방법은 무엇입니까? (0) | 2020.09.20 |
CSV 파일을 MySQL 워크 벤치로 가져 오는 방법은 무엇입니까? (0) | 2020.09.20 |
.NET WebAPI 직렬화 k_BackingField Nastiness (0) | 2020.09.20 |
angularjs 지시문에서 컨트롤러를 요구하는 방법 (0) | 2020.09.20 |