将java.math.BigDecimal映射到DB2 Numeric数据类型时发生异常



在工作中,我们使用DB2数据库,其中一个表的主键类型为Numeric。对于那个表,我创建了一个实体类,并为主键设置了BigDecimal属性。当尝试使用在该表中插入新行时

entityManager.persist(entity);

一切正常。新行已添加到表中。但问题在于,我们需要同时插入多个记录,因此我实现了这种方法:

public void addCars(final List<CarContainer> cars) throws SQLException {
    Date date = new Date();
    final java.sql.Date recDate = new java.sql.Date(date.getTime());
    final Timestamp dateCreated = new Timestamp(date.getTime());
    Session session = em.unwarp(Session.class);
    session.doWork(new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
String carsSql = "INSERT INTO " + 
                    "cars" +
                    "   (cars_id, cars_name,   
cars_rec_status, created)" +
                    "VALUES" +
                    "   (?, ?, ?, ?)";
            NullablePreparedStatement carsPreparedStatement =   
NullablePreparedStatement.wrap(connection.prepareStatement(carsSql));
            for (CarContainer carContainer : cars) {
                brandsPreparedStatement
                .setBigDecimal(1, carContainer.getCarId())
                .setString(2, carContainer.getName())
                .setShort(3, carContainer.getRecordStatus())
                .setDate(4, recDate,   
 DateUtil.getCalendarInstance());
                carsPreparedStatement.unwrap().addBatch();
        }
 carsPreparedStatement.unwrap().executeBatch();
            if (!carsPreparedStatement.unwrap().isClosed()) {
                carsPreparedStatement.unwrap().close();
            }
    });
}

这就是问题所在。当我使用本机查询时,在代码行上出现异常:

 .setBigDecimal(1, carContainer.getBrandsId())

由于某些原因,在使用本机插入时,BigDecimal未正确映射到数字。

@mustaccio感谢您的提示,但无需。我不喝伏特加或其他任何东西;)。我的问题已经解决了,问题出现在方法carContainer.getCarId()中,该方法可以进行select查询。我不知道在doWork方法中我不应该进行select查询。select之后,EntityManager正在关闭连接,并导致异常。

相关内容

最新更新