我有一个包含400万个生成实体的列表,我想将其移入表中。该实体具有类型为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;
}
但是我一直收到错误:
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.
LocalDateTime
问题? 答案 0 :(得分:2)
JPA 2.1在Java 8之前发布,因此不支持新的Date and Time API。
您可以尝试添加转换器,以获取更多检查How to persist LocalDate and LocalDateTime with JPA
@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());
}
}
或者您可以尝试不使用jdbc方法,但请使用custom JPA batch