- 在pom.xml中添加mybatis-plus依赖
<!--mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 在application.yml中配置数据库
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_test?characterEncoding=utf-8&serverTimezone=UTC
username: root
password:
driver-class-name: com.mysql.cj.jdbc.Driver
- 在cxsbg包下新建mapper包,在mapper包中新建接口,继承BaseMapper。为了避免重复在mapper接口文件上加上“@Mapper”注解,可以在启动类上加上注解“@MapperScan(“com.cxsbg.mapper”)”
package com.cxsbg.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cxsbg.domain.User;
public interface UserMapper extends BaseMapper<User> {
}
package com.cxsbg;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.cxsbg.mapper")
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class,args);
}
}
- 如果表名与实体类名不一致,可以在实体类上加上表名的注解:”@TableName(“sys_user”)“;第二种全局修改,在application.yml中添加表名前缀
mybatis-plus:
global-config:
db-config:
table-prefix: tb_
- 如果想使主键自动增长,在实体类的主键上加上注解:”@TableId(type=IdType.AUTO)“,如果要全部删除数据库的数据,可以使用sql语句”TRUNCATE TABLE 表名“。
- 如果需要字段映射,只需要在实体类的字段上加上注解”@TableField(“字段名”)“