如何在Spring中检索数据库中的一行并将其转换为对象?

发布于 2024-10-19 00:32:05 字数 2269 浏览 2 评论 0原文

我正在尝试学习如何在 Spring 2.5.6 中进行 CRUD 操作。我在数据库中创建了一个名为 Companies 的表,它有 2 个字段:id 和 name。我想要做的是使用 id 字段从表中检索一行。这就是我为此做的。

public class JdbcCompanyDao extends SimpleJdbcDaoSupport implements CompanyDao {
    protected final Log logger = LogFactory.getLog(getClass());

    public Company getCompany(int id) {
        logger.info("Getting company with id = " + id);
        Company company = getSimpleJdbcTemplate().queryForObject(
                "SELECT id, name FROM companies WHERE id = " + id,
                new CompanyMapper());
        return company;
    }

    private static class CompanyMapper implements ParameterizedRowMapper<Company> {
        public Company mapRow(ResultSet rs, int rowNum) throws SQLException {
            Company company = new Company();
            company.setId(rs.getInt("id"));
            company.setName(rs.getString("name"));
            return company;
        }
    }
}

我对其进行了单元测试,以检查我是否做得正确:

public class JdbcCompanyDaoTests extends AbstractTransactionalDataSourceSpringContextTests {
    private CompanyDao companyDao;

    public void setCompanyDao(CompanyDao companyDao) {
        this.companyDao = companyDao;
    }

    @Override
    protected String[] getConfigLocations() {
        return new String[] {"classpath:test-context.xml"};
    }

    @Override
    protected void onSetUpInTransaction() throws Exception {
        super.deleteFromTables(new String[] {"companies"});
        super.executeSqlScript("file:db/load_data.sql", true);
    }

    public void testGetCompany() {
        Company company = companyDao.getCompany(1);

        assertEquals("SomeRandomCompany", company.getName());
    }
}

当我运行测试时,出现以下错误:

org.springframework.dao.EmptyResultDataAccessException: 结果大小不正确:预期为 1, 实际0

我找不到 getCompany() 返回空结果集的原因。现在,我不知道我需要做什么,而且我仍然对 Spring 的工作原理感到困惑。它与 AbstractTransactionalDataSourceSpringContextTests 的工作方式有关吗?

附带问题:是否有任何好的资源演示如何在 Spring 中进行 CRUD 操作?到目前为止,我拥有的唯一资源是这个this 他们并没有真正为我提供足够的例子让我了解任何情况。

I'm trying to learn how to do CRUD operations in Spring 2.5.6. I made a table in my database called companies that has 2 fields: id and name. What I want to do is to retrieve a row from the table using the id field. This is what I made for it.

public class JdbcCompanyDao extends SimpleJdbcDaoSupport implements CompanyDao {
    protected final Log logger = LogFactory.getLog(getClass());

    public Company getCompany(int id) {
        logger.info("Getting company with id = " + id);
        Company company = getSimpleJdbcTemplate().queryForObject(
                "SELECT id, name FROM companies WHERE id = " + id,
                new CompanyMapper());
        return company;
    }

    private static class CompanyMapper implements ParameterizedRowMapper<Company> {
        public Company mapRow(ResultSet rs, int rowNum) throws SQLException {
            Company company = new Company();
            company.setId(rs.getInt("id"));
            company.setName(rs.getString("name"));
            return company;
        }
    }
}

I made a unit test for it to check if I did it right:

public class JdbcCompanyDaoTests extends AbstractTransactionalDataSourceSpringContextTests {
    private CompanyDao companyDao;

    public void setCompanyDao(CompanyDao companyDao) {
        this.companyDao = companyDao;
    }

    @Override
    protected String[] getConfigLocations() {
        return new String[] {"classpath:test-context.xml"};
    }

    @Override
    protected void onSetUpInTransaction() throws Exception {
        super.deleteFromTables(new String[] {"companies"});
        super.executeSqlScript("file:db/load_data.sql", true);
    }

    public void testGetCompany() {
        Company company = companyDao.getCompany(1);

        assertEquals("SomeRandomCompany", company.getName());
    }
}

When I run the test, I get the following error:

org.springframework.dao.EmptyResultDataAccessException:
Incorrect result size: expected 1,
actual 0

I can't find the reason why getCompany() is returning an empty result set. Right now, I have no idea what I need to do and I'm still confused about how Spring works. Does it have something to do with how AbstractTransactionalDataSourceSpringContextTests works?

Side question: Are there any good resources that demonstrates how to do CRUD operations in Spring? So far, the only resources I have are this and this and they don't really provide enough examples for me get anything going on.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不气馁 2024-10-26 00:32:05

只需使用 spring 中的 select.queryForList 方法即可。希望一个例子能有所帮助。

从 spring 配置 xml 文件中,您可以定义数据源。几乎任何有效的 select 语句都可以工作。以此作为您想要的起点。

<bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="${mysql.url}"/>
    <property name="username" value="${mysql.username}"/>
    <property name="password" value="${mysql.password}"/>
</bean>

用于检索数据的实际方法确实非常简单......

public List<Map<String, Object>> showTables() {

    String sql = "select name from MYTABLE..sysobjects where xtype = 'U';";

    JdbcTemplate select = new JdbcTemplate(sqlDataSource);

    return select.queryForList(sql);
}

Just use the select.queryForList method from spring. Hopefully an example will help.

From the spring configuration xml file, you define your data source. Pretty much any valid select statement will work. Use this as a starting point for what you want.

<bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="${mysql.url}"/>
    <property name="username" value="${mysql.username}"/>
    <property name="password" value="${mysql.password}"/>
</bean>

The actual method used to retrieve the data is really quite simple...

public List<Map<String, Object>> showTables() {

    String sql = "select name from MYTABLE..sysobjects where xtype = 'U';";

    JdbcTemplate select = new JdbcTemplate(sqlDataSource);

    return select.queryForList(sql);
}
彡翼 2024-10-26 00:32:05

我认为 getSimpleJdbcTemplate().queryForObject(...) 假设它在给定查询中准确找到一行,否则会引发异常。您确定您的数据库包含带有参数 id=1 的行吗?

例如,您应该使用 queryForObject() 的参数化版本,而不是将查询字符串与参数连接起来。

getSimpleJdbcTemplate().queryForObject(
            "SELECT id, name FROM companies WHERE id = ?",
            new CompanyMapper(), id)

I think that getSimpleJdbcTemplate().queryForObject(...) is assuming that it finds exactly one row with given query and raises exception otherwise. Are you sure that your database contains a row with parameter id=1?

You should use parametrized version of queryForObject() instead of concatenating query string with the parameters, for example.

getSimpleJdbcTemplate().queryForObject(
            "SELECT id, name FROM companies WHERE id = ?",
            new CompanyMapper(), id)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文