SpringBoot整合mybatis

首先导入mybatis依赖

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

 

创建mapper包,并在Application启动类中添加包扫描@MapperScan 扫描mapper文件

@SpringBootApplication
@MapperScan("com.cyitce.springcache.mapper")  //mapper 文件的包路径
public class SpringCacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCacheApplication.class, args);
    }

}

application.properties中配置数据源

spring.datasource.url=jdbc:mysql://localhost:3306/database
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=username
spring.datasource.password=password

以下是简单实现

User.java

public class User implements Serializable{

    private Long id;

    private String username;

    private String password;

    private String email;

    private String role;
    
    
    //省略get/set方法
}

 

UserMapper.java  注意添加@Mapper注解

@Mapper
public interface UserMapper {

    @Select("select * from user where id = #{id}")
    public User getUserById(Long id);
}

将UserMapper 注入到Service或者Controller中直接使用  如果出现mapper无法注入,idea报错信息请忽略(spring 容器没有找到,不影响程序启动)

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;


    @Override
    public User getUserById(Long id) {
        User userById = userMapper.getUserById(id);
        return userById;
    }
}

UserController.java

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/getUser/{id}")
    public User getUser(@PathVariable("id") String id){
        User userById = userService.getUserById(Long.parseLong(id));
        return userById;
    }
}

简单的springboot 整合mabatis就实现了。。。。

posted @ 2020-01-10 13:44  ch-一念之间  阅读(173)  评论(0编辑  收藏  举报