1 package com.cxl.demo.dao;
2
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.util.List;
6 import org.springframework.jdbc.core.JdbcTemplate;
7 import org.springframework.jdbc.core.RowMapper;
8 import com.cxl.demo.entity.User;
9 public class UserDaoImpl {
10 private JdbcTemplate jdbcTemplate;
11
12 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
13 this.jdbcTemplate = jdbcTemplate;
14 }
15
16 public List<User> getUserByName(String username) {
17 String sql = "select * from t_user where username = ?";
18 Object[] params = new Object[] { username };
19 List<User> users = null;
20 /**
21 * 使用接口实现类
22 */
23 users = jdbcTemplate.query(sql, params, new UserRowMapper());
24 /**
25 * 使用匿名内部类
26 * 如果UserRowMapper类只使用一次,单独为其创建一个类多余,可以使用匿名类
27 * 省略了书写一个实现类
28 */
29 users = jdbcTemplate.query(sql, params,
30 new RowMapper<User>() {
31 @Override
32 public User mapRow(ResultSet rs, int rowNum) throws SQLException {
33 User user = new User();
34 user.setId(rs.getInt("id"));
35 user.setUsername(rs.getString("username"));
36 user.setPassword(rs.getString("password"));
37 return user;
38 }
39 });
40 return (users != null && users.size() > 0) ? users : null;
41 }
42
43 public class UserRowMapper implements RowMapper<User> {
44
45 @Override
46 public User mapRow(ResultSet rs, int rowNum) throws SQLException {
47 User user = new User();
48 user.setId(rs.getInt("id"));
49 user.setUsername(rs.getString("username"));
50 user.setPassword(rs.getString("password"));
51 return user;
52 }
53
54 }
55 }
Spring中JdbcTemplate使用RowMapper
点赞
收藏