Spring Framework可以通过使用 ​List​或 ​Set​等集合类型来返回实体集合。具体实现方式可以参考以下示例:

假设有一个 ​User​实体类:

public class User {
    private Long id;
    private String name;
    // getter和setter方法省略
}
public class User {
    private Long id;
    private String name;
    // getter和setter方法省略
}
​

那么可以在DAO层中定义一个方法来查询所有的用户信息,并返回一个 ​List​:

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<User> findAll() {
        String sql = "SELECT * FROM user";
        List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return userList;
    }
}
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<User> findAll() {
        String sql = "SELECT * FROM user";
        List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return userList;
    }
}
​

在Service层中调用DAO层的方法,然后将查询到的 ​List​返回给Controller层:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public List<User> findAllUsers() {
        return userDao.findAll();
    }
}
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public List<User> findAllUsers() {
        return userDao.findAll();
    }
}


最后,在Controller层中调用Service层的方法,将返回的结果封装成 ​ResponseEntity​并返回:

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("")
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> userList = userService.findAllUsers();
        return new ResponseEntity<>(userList, HttpStatus.OK);
    }
}
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("")
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> userList = userService.findAllUsers();
        return new ResponseEntity<>(userList, HttpStatus.OK);
    }
}
​

这样就可以通过Spring Framework返回实体集合了。

文档更新时间: 2023-05-30 14:12   作者:admin