If there is a null value stored in a MySQL INT column, it will return 0 when accessed by technoligies like JPA. If 0 value also stored in the column, how can I differentiate between null and 0?
+2
A:
I can't believe, that it is so.
Change primitive type for object type in your entity(Example: int -> Integer)
foret
2010-10-19 08:43:28
Why don't you believe that `int` cannot hold `null`?
BalusC
2010-10-19 11:48:35
A:
To differentiate between 0 and NULL you should use ResultSet.wasNull() method, like here:
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();
}
barmaley
2010-10-19 12:18:12