SpringBoot集成 mybatis

1.创建项目,勾选mybatis相关依赖,mysql依赖

SpringBoot集成 mybatis

2.配置数据库连接的信息

application.yml

spring:
  datasource: # hikari
    driver-class-name: com.mysql.cj.jdbc.Driver # mysql 8
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8

mybatis:
  type-aliases-package: com.lzq.demo01_mybatis.domain #别名
  mapper-locations: classpath:com.lzq.demo01_mybatis.dao/*.xml #xml文件
  #使用注解在启动类上面配置 @MapperScan("com.wzx.demo04mybatis.dao")//存放接口
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #mybatis日志

3.编写dao层的业务接口及对应的方法

实体类
com.lzq.demo01_mybatis.domain.Person

package com.lzq.demo01_mybatis.domain;

import lombok.Data;

@Data
public class Person {
    private int id;
    private String name;
    private int age;
}

com.lzq.demo01_mybatis.dao.PersonDao

package com.lzq.demo01_mybatis.dao;

import com.lzq.demo01_mybatis.domain.Person;

import java.util.List;

public interface PersonDao {
    List<Person> findAll();
}

com/lzq/demo01_mybatis/dao/PersonDao.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lzq.demo01_mybatis.dao.PersonDao">
    <select id="findAll" resultType="person">
        select * from person
    </select>
</mapper>

src/main/java/com/lzq/demo01_mybatis/Demo01MybatisApplication.java
在启动项目的类上要添加注解扫描接口

package com.lzq.demo01_mybatis;

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

@SpringBootApplication
@MapperScan("com.lzq.demo01_mybatis.dao")
public class Demo01MybatisApplication {

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

}

4. Spring Boot集成Mybatis测试


import com.lzq.demo01_mybatis.dao.PersonDao;
import com.lzq.demo01_mybatis.domain.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class Demo01MybatisApplicationTests {

    @Autowired
    PersonDao dao;
    @Test
    void contextLoads() {
        List<Person> list = dao.findAll();
        System.out.println(list.get(0));
    }
}

SpringBoot集成 mybatis

上一篇:仅逗oier们一笑(不定期更新中)


下一篇:2019暑假正睿集训8.5day2题解及总结