我想使用 Java8 DateTime API 中的 LocalDate
和 LocalDateTime
,
并且在值为 null
时无法坚持到 postgresql date
和 timestamp
。
异常信息:
Internal Exception: org.postgresql.util.PSQLException: ERROR: column "some_date" is of type date but expression is of type character varying
hint: You will need to rewrite or cast the expression.
position: 61
Error Code: 0
Call: INSERT INTO TEST (ID, some_date, some_timestamp) VALUES (?, ?, ?)
bind => [0, null, null]
Query: InsertObjectQuery(mypackage.TestEntity@38c9e0d6)
我对 postgresql 驱动程序和 JPA2.2 的 Maven 依赖项:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.2.0</version>
</dependency>
我在 postgresql10.1 的 test
表(没有 not null
约束):
create table test (id serial, some_date date, some_timestamp timestamp);
我的 TestEntity
类:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Entity(name="test")
public class TestEntity {
@Id
private int id;
@Column(name="some_date")
private LocalDate someDate;
@Column(name="some_timestamp")
private LocalDateTime someTimestamp;
//simple getters and setters here.
}
我的测试方法
:
public void testMethod() {
TestEntity testEntity = new TestEntity();
// IF I set both someDate and someTimestamp via setters,
//I don't get any exceptions (table data will be added successfully)
em.getTransaction().begin();
em.persist(testEntity);
em.getTransaction().commit(); //this is where the exception occurs.
}
我错过了什么?有什么解决方法吗?
编辑:
几个月后,我意识到这个问题不再发生了。可能是因为我将服务器实现从 Grizzly 切换到了 Payara5.181。
毕竟不需要自定义转换器(即使值为 null
)。
最佳答案
这看起来像是 eclipselink 中的错误 https://bugs.eclipse.org/bugs/show_bug.cgi?id=535431 .当 LocalDate 值为 null 时,没有合适的 JDBC 类型映射,默认设置为 VARCHAR,驱动程序抛出异常。
作为解决方法,我们创建了具有所需映射的 PatchedPostgreSQLPlatform,并将其设置为 eclipselink.target-database 属性的值。
public class PatchedPostgreSQLPlatform extends PostgreSQLPlatform {
/**
* Extended with java.time.* classes mappings.
*/
@Override
public int getJDBCType(Class javaType) {
if (javaType == ClassConstants.TIME_LDATE) {
return Types.DATE;
} else if (javaType == ClassConstants.TIME_LTIME) {
return Types.TIMESTAMP;
} else if (javaType == ClassConstants.TIME_LDATETIME) {
return Types.TIMESTAMP;
} else if (javaType == ClassConstants.TIME_ODATETIME) {
return Types.TIMESTAMP;
} else if (javaType == ClassConstants.TIME_OTIME) {
return Types.TIMESTAMP;
} else {
return super.getJDBCType(javaType);
}
}
}
关于当 LocalDate 为 null 时,Java 8 LocalDate JPA 2.2 坚持到 postgresql Date 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48658346/