spring boot 快速整合mybatis

1.新建maven工程

新建数据库,导入sql脚本

2.写入如下依赖
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.2.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
3.编写配置文件
mybatis.type-aliases-package=com.example.sbmb.model

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = myuser
spring.datasource.password = mypassword
4.编写实体类
package com.example.sbmb.model;

/**
 * description: User
 *
 * @author zhangzh
 * @version [1.0, 2018/5/28]
 */
public class User {
    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
5.编写mapper
package com.example.sbmb.mapper;

import com.example.sbmb.model.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * description: UserMapper
 *
 * @author zhangzh
 * @version [1.0, 2018/5/28]
 */
public interface UserMapper {

    @Select("SELECT * FROM user")
    List getAll();
}

6.注册mapper
package com.example.sbmb;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.sbmb.mapper")
public class SbmbApplication {

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

7.调用
package com.example.sbmb.controller;

import com.example.sbmb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * description: UserController
 *
 * @author zhangzh
 * @version [1.0, 2018/5/28]
 */
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @GetMapping("/users")
    public String getAll(){
        return userMapper.getAll().toString();
    }
}

小结

这种极简方式很适合微服务的开发,联表查询比较少,不再使用xml的方式。
代码地址:
https://github.com/zzh7982/spring-boot-mybatis.git

你可能感兴趣的:(spring boot 快速整合mybatis)