Spring中JdbcTemplate中使用RowMapper
阿新 • • 發佈:2018-03-27
mapr bsp demo except pla map tin package not
Spring中JdbcTemplate中使用RowMapper
博客分類:- spring
- 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;
- }
- }
- }
Spring中JdbcTemplate中使用RowMapper