为什么Spring RowMapper只返回结果集中的最后一条记录?

时间:2015-04-07 19:14:24

标签: java spring jdbctemplate ojdbc

我正在尝试使用sql查询语句从2个数据库表(ADMIN_USER和PROVIDERS)中检索(具有提供者的用户)

"Select ADMIN_USER.ID UserID, ADMIN_USER.USER_NAME Name, ADMIN_USER.PASSWORD Password, ADMIN_USER.FULL_NAME fullName , ADMIN_USER.PRIVILEGE, ADMIN_USER.PROVIDER_ID ,PROVIDERS.ID providerID,PROVIDERS.USER_NAME provider from ADMIN_USER,PROVIDERS where ADMIN_USER.PROVIDER_ID=PROVIDERS.ID",

这是我的方法  `public List getUsers(){

    return DS.query(sqlQuery,new RowMapper<User>() {

                        public User mapRow(ResultSet rs, int rowNum)
                                throws SQLException {

                            User user = new User();
                            user.setId(rs.getInt("UserID"));
                            user.setUserName(rs.getString("Name"));
                            user.setPassword(rs.getString("Password"));
                            user.setFullName(rs.getString("fullName"));
                            user.setPrivilage(rs.getString("PRIVILEGE"));

                            Provider provider=new Provider();
                            provider.setId(rs.getInt("providerID"));
                             provider.setName(rs.getString("provider"));
                             user.setProvider(provider);

                            return user;    }}); }` 

但它只返回Method(结果集)中的最后一条记录,因为list.size()显示的是size = 1而不是4!

我认为连接是正确的,因为结果记录显示正确的连接,但我认为RowMapper中的问题?

是否有另一种方法或方法可以使用(spring,JDBC,NamedParameterJdbcTemplate)从2个连接表中检索数据?

提前致谢

1 个答案:

答案 0 :(得分:0)

以下是使用spring的NamedParameterJdbcTemplate

尝试完成的示例
public class UserRepo {

    private NamedParameterJdbcTemplate jdbcTemplate;

    private static final String sqlQuery = "Your query here";


    //Assuming you are using spring and have a datasource bean defined named datasource
    @Autowired
    public UserRepo(Datasource datasource) {
        this.jdbcTemplate = new NamedParameterJdbcTemplate(datasource);
    }

    public List<User> getUsers() {
       List<User> results = jdbcTemplate.query(sqlQuery, new UserMapper());
    }

    private static final class UserMapper implements
                RowMapper<User> { 

        mapRow(ResultSet rs, int rowNum) throws SQLException {

        User user = new User();
        user.setId(rs.getInt("UserID"));
        user.setUserName(rs.getString("Name"));
        user.setPassword(rs.getString("Password"));
        user.setFullName(rs.getString("fullName"));
        user.setPrivilage(rs.getString("PRIVILEGE"));

        Provider provider=new Provider();
        provider.setId(rs.getInt("providerID"));
        provider.setName(rs.getString("provider"));
        user.setProvider(provider);

        return user;    
        }
    }
}