SpringBoot2.0学习之集成mybatis

SpringBoot2.0学习之集成mybatis

1. 在pom.xml中引入mybatis和mysql的依赖


        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        
        
        
            mysql
            mysql-connector-java
            5.1.47
        

2. application.yml中添加数据库连接的配置

### mybatis配置
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/marklife?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: root123

3. 测试,代码如下:

mapper:

public interface UserMapper {
    @Insert("insert into t_user(name, age) values(#{name},#{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);
}

service:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Override
    public int insert(String name, Integer age) {
        return userMapper.insert(name, age);
    }
}

controller:

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/insert")
    public String insert(String name, Integer age){
        userService.insert(name, age);
        return "success";
    }
}

注意:添加扫包注解

需要在Mapper上添加@Mapper注解

在这里插入图片描述

或者在启动类上添加@MapperScan注解

在这里插入图片描述

两种选一种,建议第二种,第一种太麻烦而且容易忘记。

测试结果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


你住的城市下雨了,很想问你有没有带伞,可是我忍住了。因为我怕你说没带,我笑出声来(~^^)。

你可能感兴趣的:(springboot2.0学习)