我正在尝试使用 JPA 从 Java 对 Oracle DB 表执行插入操作。
以下是我的代码:
String coCode;
String coDescription;
/* some operations on data ... */
String queryStatement =
"insert into MANAGER_DATA (CO_CODE, CO_DESCRIPTION) values (?1, ?2)";
Query updateQuery = getEntityManager(context).createNativeQuery(queryStatement);
updateQuery.setParameter(1, coCode);
updateQuery.setParameter(2, coDescription.compareTo("") == 0 ? null : coDescription);
updateQuery.executeUpdate();
问题是,在空字符串的情况下,coDescription
可以为 null,在这种情况下,我也希望将 null 值添加到表中(coCode
是主键,但 coDescription
可以为 null)。显然,我无法像上面那样直接将 null
值传递给 setParameter
函数。
如何解决这个问题并允许将空值添加到我的数据库表中?
最佳答案
看起来您可能正在使用受 HHH-9165 createNativeQuery's setParameter does not support null 影响的旧 Hibernate 版本漏洞。升级到 Hibernate 5.0.2 或更高版本即可解决该问题。正如提到的 Jira:
Just tested it with Hibernate 5.0.2 and the bug seems to be resolved.
关于java - 如何使用 JPA 处理 INSERT 中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52990517/