如果MySQL INT列中存储了空值,则当由JPA等技术访问时,它将返回0。如果0值也存储在列中,我如何区分null和0?
答案 0 :(得分:5)
我无法相信,就是这样 更改实体中对象类型的基元类型(例如:int - > Integer)
答案 1 :(得分:2)
要区分0和NULL,您应该使用ResultSet.wasNull()方法,如下所示:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
st.executeUpdate("create table survey (id int,name varchar(30));");
st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
st.executeUpdate("insert into survey (id,name ) values (2,null)");
st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
while (rs.next()) {
String name = rs.getString(2);
if (rs.wasNull()) {
System.out.println("was NULL");
} else {
System.out.println("not NULL");
}
}
rs.close();
st.close();
conn.close();
}
答案 2 :(得分:1)
我解决它的方法如下:
Integer id;
Object o = rs.getObject("ID_COLUMN");
if(o!=null){
id = (Integer) o;
} else {
id = null;
}