QueryRunner插入方法返回类型

时间:2015-05-10 20:07:10

标签: java sql spring apache-commons-dbutils

我在其文档中根据QueryRunner#insert方法使用Apache Commons DBUtils,插入返回ResultSetHandler的泛型类型。我的项目中有一个BR_Author对象。

BR_Author.java

import org.springframework.stereotype.Repository;

@Repository
public class BR_Author {
    private int id;
    private String authorName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }
}

我在服务类中编写一个简单的insert语句,如

AuthorService#createAuthor

public BR_Author createAuthor(String authorName) throws ApiException {
        String sql = "Insert into BR_AUTHOR(authorName) VALUES(?)";
        ResultSetHandler<BR_Author> rs = new BeanHandler<BR_Author>(
                BR_Author.class);
        QueryRunner qr = new QueryRunner(dataSource);
        Object[] params = { authorName };
        try {
            BR_Author author = qr.insert(sql, rs, params);
            System.out.println("Br_Author:" + author);
            return author;

        } catch (SQLException e) {
            throw new ApiException(ErrorCode.ERR20001, e.getMessage());
        }
    }

我试图在createAuthor方法中返回添加的值,但是如果我将id字段配置为自动增量对象返回为

Br_Author:Br_Author [id=0, authorName=null]

当我检查数据库时,我看到它成功添加了值。

如果我禁用自动增量并从代码设置id,则author对象为null。所以我想知道我误解了QueryRunner#insert方法或者它有一个bug。我已经查看了下面的链接。

BTW: 选择适合BR_Author类的查询,这意味着不应存在任何映射问题。

1 个答案:

答案 0 :(得分:0)

我没有从DBUtils API找到任何官方解决方案,所以我只返回生成的ID,然后在服务层插入带有此ID的记录后查询它。这种方法在服务层返回Object,但我做了一个额外的查询。