简体   繁体   English

使用JDBC的Spring插入

[英]Spring insert using jdbc

I have a table in SQLYog where one column is varchar limit to 200 length. 我在SQLYog中有一张表,其中一列是varchar限制为200个长度。 I wrote the method below for the insert, but when testing the code the column "Name" is not been filled by the data in the DB. 我在下面为插入编写了方法,但是在测试代码时,数据库中的数据未填充“名称”列。

@Override
public void insert(final List<InfoRow> rows) {
    String sql = "INSERT INTO info_table (ID, NAME, AGE) VALUES (?, SUBSTRING(?, 0, 200), ?)";

    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

        @Override
        public void setValues(PreparedStatement ps, int i)
                throws SQLException {
            InfoRow row= rows.get(i);
            ps.setInt(1, (int) row.getId());
            ps.setString(2, row.getName());
            ps.setInt(3,(int) row.getAge());
        }

        @Override
        public int getBatchSize() {
            return rows.size();
        }
    });

}

What is the correct way to validate the 'Name' size while insert? 插入时验证“名称”大小的正确方法是什么?

Thanks! 谢谢!

Substring expressions in MySQL (this is a guess based on the sqlyog tag) are 1 based, not 0 based. MySQL中的子字符串表达式(这是基于sqlyog标记的猜测)基于1,而不是基于0。 Try this instead: 尝试以下方法:

SUBSTRING(?, 1, 200)

Generally, I would keep validation logic out of the database layer, and handle "bad input" in the application layer. 通常,我会将验证逻辑置于数据库层之外,并在应用程序层中处理“错误输入”。 This allows me to log the fact that data would be dropped/truncated. 这使我可以记录数据将被删除/截断的事实。

But this approach is fine. 但是这种方法很好。

The correct way to validate inputs is in your service layer not your model layer like you are describing here. 验证输入的正确方法是在服务层中,而不是您在此处描述的模型层中。 The DAO should be responsible just for persist data not to validate. DAO应该仅负责持久性数据的验证。

You should have a service calling the insert(List<InfoRow>); 您应该有一个调用insert(List<InfoRow>); method and there have to be your validation. 方法,并且必须进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM