SpringBoot整合通用Mapper(MyBatis)

导包

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

<!--连接池-->
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-jdbc</artifactId>-->
<!--</dependency>-->
<!--mybatis -->
<!--<dependency>-->
<!--<groupId>org.mybatis.spring.boot</groupId>-->
<!--<artifactId>mybatis-spring-boot-starter</artifactId>-->
<!--<version>1.3.2</version>-->
<!--</dependency>-->
<!--通用mapper,依赖导入了以上两个启动器-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>

启动器

package com.company;

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

@SpringBootApplication
@MapperScan("com.company.mapper")//扫描接口,注意要使用通用Mapper包的注解
public class BootDemoApplication {

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

配置application.yaml

  

#配置com.zaxxer:HikariCP:3.4.1连接池
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
username: root
password: root

#整合mybatis
mybatis:
#启用别名,配置实体类路径
type-aliases-package: com.company.pojo

实体类

package com.company.pojo;

import lombok.Data;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
@Data
@Table(name="tb_user")//指定表名
public class User {
@Id//主键
@KeySql(useGeneratedKeys = true)//自动增长
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
//1男,2女
private Integer sex;
private Date birthday;
private String note;
private Date created;
// @Transient 忽略该字段
private Date updated;
}

接口

package com.company.mapper;

import com.company.pojo.User;
import tk.mybatis.mapper.common.Mapper;
//继承通用Mapper的Mapper接口,指定泛型为对应实体类
public interface UserMapper extends Mapper<User>{
}

这样通用Mapper就会生成单表的通用方法及sql

 当你引入

spring-boot-starter-jdbc启动器的时候
SpringBoot就已经为我们配置好事务控制了,只需要在service中需要事务的方法上加上@Transactional注解即可
posted @ 2020-03-25 14:52  荒野猛兽  阅读(4393)  评论(0编辑  收藏  举报