views:

52

answers:

1
+1  Q: 

Spring JDBC DAO

Hi! Im learning Spring (2 and 3) and i got this method in a 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);
}

and the following Spring wiring:

<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>

The things is that i dont like the commented lines of java code (1) and (2). I'm going to start with (2) which i think is the easy one: is there a way i can wire the bean in the .xml file to tell spring to instantiate a set implementation for the 'accounts' set in ClientImpl? so i can get rid of (2)

Now moving on to (1): what happens if the implementation changes ? do i really need to write another DAO for a different implementation? or do i have to construct a BeanFactory ? or is there another more beautiful solution ?

Thanks!

A: 

I'm a bit confused here - why have you defined a ClientImpl bean in your XML, but not using it in your Java?

Your already have most of the solution, you just need to fetch a new ClientImpl from Spring each iterations through the loop:

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);
}

With this approach, the actual construction and initialization of ClientImpl is done by Spring, not your code.

skaffman
Thanks. I dont know why i though that having a Factory in the DAO was bad. Now it seems ok. I must be tired.
Blitzkr1eg