Spring中JdbcTemplate中使用RowMapper
博客分类:
Java代码
- package com.cxl.demo.dao;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.List;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.core.RowMapper;
- import com.cxl.demo.entity.User;
- public class UserDaoImpl {
- private JdbcTemplate jdbcTemplate;
- public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
- this.jdbcTemplate = jdbcTemplate;
- }
- public List<User> getUserByName(String username) {
- String sql = "select * from t_user where username = ?";
- Object[] params = new Object[] { username };
- List<User> users = null;
- /**
- * 使用接口实现类
- */
- users = jdbcTemplate.query(sql, params, new UserRowMapper());
- /**
- * 使用匿名内部类
- * 如果UserRowMapper类只使用一次,单独为其创建一个类多余,可以使用匿名类
- * 省略了书写一个实现类
- */
- users = jdbcTemplate.query(sql, params,
- new RowMapper<User>() {
- @Override
- public User mapRow(ResultSet rs, int rowNum) throws SQLException {
- User user = new User();
- user.setId(rs.getInt("id"));
- user.setUsername(rs.getString("username"));
- user.setPassword(rs.getString("password"));
- return user;
- }
- });
- return (users != null && users.size() > 0) ? users : null;
- }
- public class UserRowMapper implements RowMapper<User> {
- @Override
- public User mapRow(ResultSet rs, int rowNum) throws SQLException {
- User user = new User();
- user.setId(rs.getInt("id"));
- user.setUsername(rs.getString("username"));
- user.setPassword(rs.getString("password"));
- return user;
- }
- }
- }
原文地址:https://www.cnblogs.com/mybatis/p/8657663.html
时间: 2024-10-01 10:58:07