SSM-Spring-Spring和数据库编程-JDBC代码时空的解决方案

SSM-Spring-Spring和数据库编程-JDBC代码时空的解决方案-jdbcTemplate

​ jdbcTemplate是Spring针对JDBC代码失控提供的解决方案,在这个方案中体现了Spring框架的主导思想:给予常用技术提供模板化的编程,减少开发者的工作量

配置:

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

​ 这样就配置了一个jdbcTemplate的Bean


jdbcTemplate的增,删,改,查

public class Test {
    
    
    public static void main(String[] args) {
    
    

        ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring/spring07.xml");
        JdbcTemplate  jdbcTemplate=ctx.getBean(JdbcTemplate.class);
        Test test=new Test();
        test.insertRole(jdbcTemplate);
        List roleList=test.findRole(jdbcTemplate,"role");
        System.out.println(roleList.size());
        Role role=new Role();
        role.setId(1L);
        role.setRoleName("undata_role_name_1");
        role.setNote("update_note_1");
        test.updateRole(jdbcTemplate,role);
        test.deleteRole(jdbcTemplate,1L);
    }

    //增
    public int insertRole(JdbcTemplate jdbcTemplate){
    
    
        String roleName="role_name1";
        String note="note1";
        String sql="insert into t_role(role_name,note) values(?,?)";
        return jdbcTemplate.update(sql,roleName,note);
    }
    //删
    public int deleteRole(JdbcTemplate jdbcTemplate,Long id){
    
    
        String sql="delete from t_role where id=?";
        return  jdbcTemplate.update(sql,id);
    }
    //改
    public  int updateRole(JdbcTemplate jdbcTemplate, Role role){
    
    
        String sql="update t_role set role_name=? ,note=? where id=?";
        return jdbcTemplate.update(sql,role.getRoleName(),role.getNote(),role.getId());
    }
    //查
    public List<Role> findRole(JdbcTemplate jdbcTemplate,String roleName){
    
    
        String sql="select id,role_name,note from t_role where role_name like concat('%',?,'%')";
        Object[] params={
    
    roleName};
        //使用RowMapper接口组织返回
        List<Role> list=jdbcTemplate.query(sql,params,(ResultSet rs,int rowNum)->{
    
    
            Role result=new Role();
            result.setId(rs.getLong("id"));
            result.setRoleName(rs.getString("role_name"));
            result.setNote(rs.getString("note"));
            return result;
        });
        return list;
    }
}

执行多条SQL

​ 使用execute方法。它将允许传递ConnectionCallback或者StatementCallback等接口进行回调

猜你喜欢

转载自blog.csdn.net/weixin_43958223/article/details/115317626