我有一個奇怪的問題在這裏奇怪的問題。有關比較春DAO的整數結果
燮實體:
public class Sup implements Serializable {
private static final long serialVersionUID = 5898846627874143178L;
private Integer state;
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}
代碼1:
@Override
public void test() {
for (int i = 0; i < 10; i++) {
//Just a simple query sql,the result is always the same
//and the state of 'sup' is always 0;
Sup sup = supDao.querySupByid(40017);
Integer state = sup.getState();
System.out.println("my state:" + state);
if (state!=Integer.valueOf(0)) {
System.out.println(" ["+ i + "]>>>>0!=0");
}
}
}
的querySupByid方法:
@Select("SELECT state FROM TBL_SUP WHERE ID=#{supId} ")
Sup querySupByid(@Param("supId")Integer sup);
這樣結果的一部分:
- 我的狀態:0
- 我的狀態:0
- [1] >>>> 0 = 0
- 我的狀態:!0
- [2] >>>> 0 = 0
- 我的狀態:0
- [3] >>>> 0 = 0
....
我預期的結果是 「我的狀態:0」 的10! 正如你所看到的,大多數的結果預計在第一循環都是錯誤的(state!=Integer.valueOf(0)
原因的狀態總是0,因此這裏應該永遠是假的),然後我改變了這樣的
代碼2一些代碼:
@Override
public void test() throws InterruptedException {
for (int i = 0; i < 10; i++) {
Sup sup = supDao.querySupByid(40017);
Integer state = sup.getState();
System.out.println("my state:" + state);
TimeUnit.SECONDS.sleep(5);
if (state!=Integer.valueOf(0)) {
System.out.println(" ["+ i + "]>>>>0!=0");
}
}
}
在每一個循環我停頓5秒鐘,結果變成了這樣:
- 我的狀態:0
- 我的狀態:0
- 我的狀態:0
- 我的狀態:0
- 我的狀態:0
- 我的狀態:0
- 我的狀態:0
- 我的狀態:0
- 我的狀態:0
- 我的狀態:0
清楚我已經得到了正確的結果終於; 接下來我再次更改代碼;
CODE3:
@Override
public void test() throws InterruptedException {
for (int i = 0; i < 10; i++) {
Sup sup = new Sup();//supDao.querySupByid(40017);
sup.setState(0);
Integer state = sup.getState();
System.out.println("my state:" + state);
if (state!=Integer.valueOf(0)) {
System.out.println(" ["+ i + "]>>>>0!=0");
}
}
}
在CODE3結果也是正確的,我改變了再次驗證碼:
碼4:
@Override
public void test() throws InterruptedException {
for (int i = 0; i < 10; i++) {
Sup sup =supDao.querySupByid(40017);
Integer state = sup.getState();
System.out.println("my state:" + state);
if (!state.equals(Integer.valueOf(0))) {
System.out.println(" ["+ i + "]>>>>0!=0");
}
}
}
與CODE3相同的結果,但我無法弄清楚合理的解釋。
我已經想通了,結果是由緩存引起的;第一個結果已經被序列化爲緩存,從緩存中得到的以下結果被反序列化了。所以後面的結果不是前者的結果「==」一個愚蠢的錯誤
「正如你所看到的,大部分的結果都是錯誤的」 - 不,我不明白爲什麼這個結果是錯誤的,你沒有解釋什麼是「好」的結果。你獲取10次相同的實體,並且所有的狀態都是相同的,在你的情況下是0。我沒有看到它會在迭代中有什麼不同。 – Antoniossss
當比較盒裝原語,總是用'equals',沒有'=='或'!='。後者測試對象身份。 – Henry
的解釋是sup.getState的'()的執行'和'supDao.querySupByid(40017)'。我們需要看到這一點。 – Henry