Spring 使用namedParameterJdbcTemplate保存LocalDateTime
我有一个400万个生成实体的列表,我想将其移动到表中。实体具有类型为Spring 使用namedParameterJdbcTemplate保存LocalDateTime,spring,spring-boot,Spring,Spring Boot,我有一个400万个生成实体的列表,我想将其移动到表中。实体具有类型为LocalDateTime的字段: @Data @AllArgsConstructor @Entity @Table(name = "invoices") public class Invoice { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) Long id; @Column(name = "exact_iss_time")
LocalDateTime
的字段:
@Data
@AllArgsConstructor
@Entity
@Table(name = "invoices")
public class Invoice {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
Long id;
@Column(name = "exact_iss_time")
private LocalDateTime exactIssueTime;
@Column(name = "final_iss_time")
private LocalDateTime finalIssueTime;
@Column(name = "issuer")
private String issuer;
@Column(name = "groupid")
private Integer groupID;
protected Invoice() {
}
}
由于有大量的实体,我希望以最佳方式执行此操作,这与NamedParameterJdbcTemplate.batchUpdate()
类似:
public int[] bulkSaveInvoices(List<Invoice> invoices){
String insertSQL = "INSERT INTO invoices VALUES (:id, :exactIssueTime, :finalIssueTime, :issuer, :groupID)";
SqlParameterSource[] sqlParams = SqlParameterSourceUtils.createBatch(invoices.toArray());
int[] insertCounts = namedParameterJdbcTemplate.batchUpdate(insertSQL, sqlParams);
return insertCounts;
}
LocalDateTime
问题李>
JPA2.1是在Java8之前发布的,因此不支持新的日期和时间API 您可以尝试添加转换器,以进行更多检查
@转换器(autoApply=true)
公共类LocalDateTimeAttributeConverter实现AttributeConverter{
@凌驾
公共时间戳convertToDatabaseColumn(LocalDateTime locDateTime){
返回(locDateTime==null?null:Timestamp.valueOf(locDateTime));
}
@凌驾
公共LocalDateTime convertToEntityAttribute(时间戳sqlTimestamp){
返回(sqlTimestamp==null?null:sqlTimestamp.toLocalDateTime());
}
}
或者您可以尝试不使用jdbc方法,但使用检查这个-,我使用更多的JPA方法您必须使用jdbc 4.2(和兼容的驱动程序),或者在将
LocalDateTime
插入数据库之前将其转换为Timestamp
。或者假设您正在使用hibernate使用JPA批量插入,或者使用hibernate0-java8
,或者如果您使用的是hibernate 5.2,您可以直接插入它。
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [INSERT INTO invoices VALUES (?, ?, ?, ?, ?)]; nested exception is org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of java.time.LocalDateTime. Use setObject() with an explicit Types value to specify the type to use.
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
return (locDateTime == null ? null : Timestamp.valueOf(locDateTime));
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
return (sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime());
}
}