mybatis 在springboot中的使用

1、pom文件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

       <!--mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

       <!--druid数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>

2、配置文件

spring:
  application:
    name: mybatisDemo
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://192.168.20.35:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: root
    password: 12345678
mybatis:
    mapper-locations: classpath:/mapper/*.xml
    #config-location: classpath:mybatis/mybatis-config.xml   # mybatis 配置文件 位置
    configuration:     # mybatis 配置 替代 config-location
       map-underscore-to-camel-case: true

使用了数据源 DruidDataSource
mapper 映射文件放在 resources/mapper 文件夹下
mapper 接口文件放在 com.example.mybatisdemo.mapper 包下,com.example.mybatisdemo为项目跟目录
可以不写全局配置文件,所有全局配置文件的配置都放在configuration配置项中即可

3、 项目主启动文件, 添加扫描

@MapperScan("com.example.mybatisdemo.mapper")
@SpringBootApplication
public class MybatisDemoApplication {

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

}

在启动文件中添加了 mapper 接口扫描@MapperScan,就可以不用在每个 mapper 接口中 加 @Mapper 注解

4、接口


public interface AcMapper {
    int insert(Ac record);

    @Select("select * from ac where id = #{id}")
    Ac selectByUserId(Integer id);
}

5、映射文件

  <insert id="insert" keyColumn="No" keyProperty="no" parameterType="com.example.mybatisdemo.domain.Ac" useGeneratedKeys="true">
    insert into ac (id, `time`, ac) values (#{id}, #{time}, #{ac} )
  </insert>

https://www.yuque.com/atguigu/springboot/aob431

https://github.com/alibaba/druid

posted @ 2021-08-02 15:04  zhanglw  阅读(193)  评论(0)    收藏  举报