【问题标题】:Spring JDBC DAOSpring JDBC DAO
【发布时间】:2010-09-02 18:27:26
【问题描述】:

我正在学习 Spring(2 和 3)并且我在 ClientDao 中得到了这个方法

    public Client getClient(int id) {
    List<Client> clients= getSimpleJdbcTemplate().query(
            CLIENT_GET,
            new RowMapper<Client>() {
                public Client mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Client client = new ClientImpl(); // !! this (1)
                    client.setAccounts(new HashSet<Account>()); //  !! this (2)
                    client.setId(rs.getInt(1));
                    client.setName(rs.getString(2));
                    return client;
                }
            },id
            );
    return clients.get(0);
}

以及以下 Spring 接线:

<bean id="account" class="client.AccountRON" scope="prototype">
    <property name="currency" value = "RON" />
    <property name="ammount" value="0" />

</bean>     
<bean id="client" class="client.ClientImpl" scope="prototype">
    <property name="name" value="--client--" />
    <property name="accounts">
        <set>
        </set>
    </property>
</bean>

问题是我不喜欢 java 代码 (1) 和 (2) 的注释行。 我将从 (2) 开始,我认为这很简单:有没有一种方法可以连接 .xml 文件中的 bean 来告诉 spring 为 ClientImpl 中的“帐户”集实例化一个集实现?所以我可以摆脱(2)

现在转到(1):如果实现发生变化会发生什么?我真的需要为不同的实现编写另一个 DAO 吗?还是我必须构建一个 BeanFactory ?还是有其他更漂亮的解决方案?

谢谢!

【问题讨论】:

    标签: java spring jdbc dao


    【解决方案1】:

    我有点困惑——为什么你在你的 XML 中定义了一个 ClientImpl bean,而不是在你的 Java 中使用它?

    您已经有了大部分解决方案,您只需通过循环每次迭代从 Spring 获取一个新的ClientImpl

    private @Autowired BeanFactory beanFactory;
    
    public Client getClient(int id) {
        List<Client> clients= getSimpleJdbcTemplate().query(
                CLIENT_GET,
                new RowMapper<Client>() {
                    public Client mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Client client = beanFactory.getBean(Client.class);
                        client.setId(rs.getInt(1));
                        client.setName(rs.getString(2));
                        return client;
                    }
                },id
        );
        return clients.get(0);
    }
    

    使用这种方法,ClientImpl 的实际构造和初始化由 Spring 完成,而不是您的代码。

    【讨论】:

    • 谢谢。我不知道为什么我认为在 DAO 中有一个工厂是不好的。现在看来还可以。我一定累了。
    猜你喜欢
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 2018-01-07
    • 2011-10-27
    相关资源
    最近更新 更多