JPA Native Query设置null参数

这是我的代码部分:

Query q = em.createNativeQuery("insert into table_name (value_one, value_two, value_three) values (?,?,?)"); q.setParameter(1, value1); q.setParameter(2, value2); q.setParameter(3, value3); q.executeUpdate(); 

value3有时可以为null(Date类对象)。 如果为null,则抛出以下exception:

  Caused by: org.postgresql.util.PSQLException: ERROR: column "value_three" is of type timestamp without time zone but expression is of type bytea Hint: You will need to rewrite or cast the expression. Position: 88 at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334) at org.hibernate.engine.query.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:189) ... 11 more 

如何使这段代码工作并将空值保存到数据库中?

你正在使用postgresql(已经是堆栈告诉了),可能是Hibernate,几乎肯定会遇到这个问题: PostgreSQL JDBC Null String作为bytea

我使用了这个特定的解决方案: https : //stackoverflow.com/a/23501509/516188

这意味着转义为Hibernate API,因此您可以提供表达式的类型。

在我的情况下,它是一个可以为空的Short,所以我用过:

.setParameter("short", shortValue, ShortType.INSTANCE);

shortValue属于Short类型。

如果你没有使用Hibernate,但是你正在使用EclipseLink,你可以使用查询提示: https : //wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Query_Hints

示例查询:

 String insert = "INSERT INTO mytable VALUES ( ?, ?, ?, ?)"; em = getEntityManager(); em.getTransaction().begin(); Query u = em.createNativeQuery(insert); u.setHint(QueryHints.BIND_PARAMETERS, HintValues.FALSE);//<--the hint u.setParameter(1, "value1"); u.setParameter(2, "value2"); u.setParameter(4, "value4");//just skipped the null element u.executeUpdate(); em.getTransaction().commit(); 

结果将是一个插入:

 mytable column1 column2 column3 column4 value1 value2 value4 

当然如果“column3”在db中可以为空...

我不知道是否也适用于Hibernate,但它可以。 我使用PostgreSQL进行测试。