gpt4 book ai didi

java - Spring JDBC DAO

转载 作者:行者123 更新时间:2023-12-04 06:46:55 25 4
gpt4 key购买 nike

我正在学习 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) 开始,我认为这很简单:有没有一种方法可以将 bean 连接到 .xml 文件中,以告诉 spring 为 ClientImpl 中设置的“帐户”实例化一个集合实现?所以我可以摆脱(2)

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

谢谢!

最佳答案

我在这里有点困惑 - 为什么你定义了 ClientImpl bean 在您的 XML 中,但不在您的 Java 中使用它?

您已经拥有大部分解决方案,您只需要获取一个新的 ClientImpl从 Spring 开始每次迭代循环:

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 完成,而不是您的代码。

关于java - Spring JDBC DAO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3630028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com