spring-JDBC

//bean
public class User {
    private Integer id;
    private String name;
    private String password;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
//dao
public interface UserDao {
    public Integer addUser(User user);
    public List getAll();
}
//daoImpl
@Repository
public class UserDaoImpl  implements UserDao {
    @Resource
    private JdbcTemplate jdbcTemplate;
    public Integer addUser(User user) {
        String sql = "insert into user(name,password) values(?,?)";
        return this.jdbcTemplate.update(sql, user.getName(),user.getPassword());
    }
    public List getAll(){
         String sql = "select * from user";
         return this.jdbcTemplate.query(sql, new UserRowMapper());
    }
     private class UserRowMapper implements RowMapper {
         public User mapRow(ResultSet rs, int rowNum) throws SQLException {
             User user = new User();
             user.setId(rs.getInt("id"));
             user.setName(rs.getString("name"));
             user.setPassword(rs.getString("password"));
             return user;
         }
    }
}
//application.xml


    
        
        
        
        
    
    
        
    
    
  
//junit测试代码
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:application.xml"})
public class TestCase {
    @Resource
    private UserDao userDao;
    @Test
    public void case1(){
        User user = new User();
        user.setName("zhouma");
        user.setPassword("123456");
        userDao.addUser(user);
    }
    @Test
    public void case2(){
        List all = userDao.getAll();
        for(User user:all){
            System.out.println(user.getId()+user.getName()+user.getPassword());
        }
    }
}
//maven pom

  4.0.0
  com.zma
  test-springjdbc
  0.0.1-SNAPSHOT
  
      
        org.springframework  
        spring-core  
        4.3.8.RELEASE  
     
    
        org.springframework
        spring-jdbc
        4.3.8.RELEASE
    
      
       org.springframework  
       spring-test  
       4.3.8.RELEASE  
     
      
           org.springframework  
           spring-context-support  
           4.3.8.RELEASE  
      
      
        mysql  
        mysql-connector-java  
        5.1.30  
      
      
        commons-dbcp  
        commons-dbcp  
        1.2.2  
    
    
        junit
        junit
        4.11
        test
    
  
      
          
              
                org.apache.maven.plugins  
                maven-compiler-plugin  
                  
                    1.7  
                    1.7  
                  
              
          
      

你可能感兴趣的:(spring-JDBC)