實體類中int型變量爲0,mybatis配置文件判斷爲空,解決辦法

再實體類中,定義一個int類型的字段,容易出現默認值的情況,建議解決辦法,將int改爲Integer,那麼變量可爲空

如:

public class Pojo {
	
	int a;
	Integer b;
	
	public int getA() {
		return a;
	}
	public void setA(int a) {
		this.a = a;
	}
	public Integer getB() {
		return b;
	}
	public void setB(Integer b) {
		this.b = b;
	}
	
	
	@Override
	public String toString() {
		return "Pojo [a=" + a + ", b=" + b + "]";
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + a;
		result = prime * result + ((b == null) ? 0 : b.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Pojo other = (Pojo) obj;
		if (a != other.a)
			return false;
		if (b == null) {
			if (other.b != null)
				return false;
		} else if (!b.equals(other.b))
			return false;
		return true;
	}
	
	
	
}

測試類

public class TestMain {
	public static void main(String[] args) {
		
		Pojo pojo = new Pojo();
		System.out.format("Intger和int的區別%s", pojo.toString());
		
	}
}
輸出結果

Intger和int的區別Pojo [a=0, b=null]

因爲java中int的類變量默認值爲0,對象的默認值爲null,在方法中因爲int的默認值沒有,int爲基本類型,而Integer爲對象類型,因此出現差異,所以定義變量時需要給初始值。

在mybaits中自動生成配置問文件容易出現下面情況

<if test="queryObj.userId!=null">
   and user_id like concat('%',#{queryObj.userId},'%')
</if>

如果,使用int定義變量將不能如此判斷,可將int改爲Integer

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章