小D课堂 - 零基础入门SpringBoot2.X到实战_第8节 数据库操作之整合Mybaties和事务讲解_34、SpringBoot整合Mybatis实操和打印SQL语句

笔记

3、SpringBoot2.x整合Mybatis3.x增删改查实操和控制台打印SQL语句
    讲解:SpringBoot2.x整合Mybatis3.x增删改查实操, 控制台打印sql语句
    
    1、控制台打印sql语句        
        #增加打印sql语句,一般用于本地开发测试
        mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

    2、增加mapper代码        
        @Select("SELECT * FROM user")
        @Results({
            @Result(column = "create_time",property = "createTime")  //javaType = java.util.Date.class        
        })
        List<User> getAll();
      
        @Select("SELECT * FROM user WHERE id = #{id}")
        @Results({
             @Result(column = "create_time",property = "createTime")
        })
        User findById(Long id);

        @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
        void update(User user);

        @Delete("DELETE FROM user WHERE id =#{userId}")
        void delete(Long userId);
     
     3、增加API

        @GetMapping("find_all")
        public Object findAll(){
           return JsonData.buildSuccess(userMapper.getAll());
        }
        
        @GetMapping("find_by_Id")
        public Object findById(long id){
           return JsonData.buildSuccess(userMapper.findById(id));
        }
        
        @GetMapping("del_by_id")
        public Object delById(long id){
        userMapper.delete(id);
           return JsonData.buildSuccess();
        }
        
        @GetMapping("update")
        public Object update(String name,int id){
            User user = new User();
            user.setName(name);
            user.setId(id);
            userMapper.update(user);
            return JsonData.buildSuccess();
        }

开始

 

第三方数据源的使用和不使用





把这段代码注释掉,又会去用默认的数据源


这样数据源用的就是默认的

console打印执行的sql

需要在配置文件里面加上这段话
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl


启动程序
访问接口


Updates是影响的行数

CRUD



数据字段的映射,我们在数据库内用下划线,开发的时候实体类不用下划线。所以就需要属性字段值和数据库的字段值进行映射

controller里面注入了Mapper类。在这里直接调用Mapper里面的方法

查询所有和根据id去查询。这里直接调用的是Mapper里面的方法


启动程序

返回了所有的数据


控制台可以看到打印的sql

测试findId




删除




删除id为51的数据

数据库内被删除了

update更新测试






 

posted @ 2019-08-28 17:33  高山-景行  阅读(183)  评论(0编辑  收藏  举报