Spring boot 六 整合 MyBatis

沒事偷著樂琅發表於2017-11-07

spring boot 整合MyBatis 非常簡單:

1、新增依賴包。mysql驅動 mybatis驅動(必須大於 1.1.1版本)
2、新增 application.properties 配置。
3、在 Application.main 類 新增 @MapperScan(com.zll.*)
4、新增實體物件 Student
5、編寫Student資料對映物件 StudentMapper
6、編寫Student業務邏輯層 StudentService
7、編寫對外控制層 StudentController。

1、新增依賴包。mysql驅動 mybatis驅動(必須大於 1.1.1版本)

        <!--Spring boot jpa 依賴包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--mysql 依賴包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--mybaits 依賴包-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

2、新增 application.properties 配置。

# 資料庫訪問配置
# 主資料來源,預設的
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username= root
spring.datasource.password= root
spring.datasource.driverClassName = com.mysql.jdbc.Driver


#指定資料庫
spring.jpa.database=mysql
# 是否顯示sql語句
spring.jpa.show-sql=true
# hibernate ddl auto (create create-drop update)
spring.jpa.hibernate.ddl-auto=update
# 選擇自己的 命名策略 ImprovedNamingStrategy  (比如 orderItem >> order_item)
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy

3、在 Application.main 類 新增 @MapperScan(com.zll.*)

@SpringBootApplication
@MapperScan("com.example.demo.*")//mybaits 掃描 指定報下的所有實體和對映物件。
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

4、新增實體物件 Student
不需要註解


public class Student {

    private int id;
    private String name;
    private String creditHour;

5、編寫Person資料對映物件 StudentMapper

public interface StudentMapper {

     @Insert("insert into student(name,credit_hour) value(#{name},#{creditHour})")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")//加入該註解可以保持物件後,檢視物件插入id
    public int insert(Student s);

    @Delete("delete from student where id=#{id}")
    public int delete(int id);

    @Update("update student set name=#{name},credit_hour=#{credit} where id=#{id}")
    public int update(@Param("id") int id, @Param("name") String name, @Param("credit") String credit);

    @Select("select * from student ")
    @Results({
            @Result(id = true, property = "id", column = "id", javaType = Integer.class),
            @Result(property = "creditHour", column = "credit_hour", javaType = String.class),
    })
    public List<Student> selectAll();

}

6、編寫Person業務邏輯層 StudentService

@Service
public class StudentService {

    @Resource
    private StudentMapper mStudentMapper;

    public int insert(Student s){
        mStudentMapper.insert(s);
        return s.getId();
    }


    public int delete(int id){
        return mStudentMapper.delete(id);
    }

    public int update(int id,Student s){
        return mStudentMapper.update(id,s.getName(),s.getCreditHour());
    }

    public List<Student> selectAll(){
        return mStudentMapper.selectAll();
    }

}

7、編寫對外控制層 StudentController。

@RestController
@RequestMapping("/mybaits")
public class StudentController {

    @Resource
    private StudentService mStudentService;

    @RequestMapping("/insert")
    public int insert(String name,String credit) {
        return mStudentService.insert(new Student(name,credit));
    }

    @RequestMapping("/delete")
    public int delete(int id) {
        return mStudentService.delete(id);
    }

    @RequestMapping("/update")
    public int update(int id, String name,String credit) {
        return mStudentService.update(id, new Student(name,credit));
    }

    @RequestMapping("/selectAll")
    public List<Student> selectLikeName() {
        return mStudentService.selectAll();
    }

}

注意容易出現的問題:
Mybatis錯誤:Parameter ‘XXX’ not found. Available parameters are [1, 0, param1, param2]
解決辦法:
在引數上加@Param(id)

檢視Mapper類 Update寫法

關於更多 Spring Mybatis 註解的細節 請檢視 MyBiats 註解開發系列。

相關文章