1. 程式人生 > >Spring中JdbcTemplate中使用RowMapper

Spring中JdbcTemplate中使用RowMapper

mapr bsp demo except pla map tin package not

Spring中JdbcTemplate中使用RowMapper

博客分類:
  • spring
Java代碼 技術分享圖片
  1. package com.cxl.demo.dao;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import java.util.List;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. import org.springframework.jdbc.core.RowMapper;
  7. import com.cxl.demo.entity.User;
  8. public class UserDaoImpl {
  9. private JdbcTemplate jdbcTemplate;
  10. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  11. this.jdbcTemplate = jdbcTemplate;
  12. }
  13. public List<User> getUserByName(String username) {
  14. String sql = "select * from t_user where username = ?";
  15. Object[] params = new Object[] { username };
  16. List<User> users = null;
  17. /**
  18. * 使用接口實現類
  19. */
  20. users = jdbcTemplate.query(sql, params, new UserRowMapper());
  21. /**
  22. * 使用匿名內部類
  23. * 如果UserRowMapper類只使用一次,單獨為其創建一個類多余,可以使用匿名類
  24. * 省略了書寫一個實現類
  25. */
  26. users = jdbcTemplate.query(sql, params,
  27. new RowMapper<User>() {
  28. @Override
  29. public User mapRow(ResultSet rs, int rowNum) throws SQLException {
  30. User user = new User();
  31. user.setId(rs.getInt("id"));
  32. user.setUsername(rs.getString("username"));
  33. user.setPassword(rs.getString("password"));
  34. return user;
  35. }
  36. });
  37. return (users != null && users.size() > 0) ? users : null;
  38. }
  39. public class UserRowMapper implements RowMapper<User> {
  40. @Override
  41. public User mapRow(ResultSet rs, int rowNum) throws SQLException {
  42. User user = new User();
  43. user.setId(rs.getInt("id"));
  44. user.setUsername(rs.getString("username"));
  45. user.setPassword(rs.getString("password"));
  46. return user;
  47. }
  48. }
  49. }

Spring中JdbcTemplate中使用RowMapper