使用namedParameterJdbcTemplate保存LocalDateTime

时间:2017-03-20 20:07:07

标签: 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")
    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.
  1. 我这样做是对的 - 如果是这样的话,如何在这种情况下解决这个LocalDateTime问题?
  2. 如果这是错误的方式,那么使用Spring-boot将400万个生成的测试实体添加到表中的最佳方式是什么? INSERT 数据库?

1 个答案:

答案 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