mybatis plus 项目模板
前言
项目搭建
- 新建1个spring boot项目,导入所需依赖
点击查看详情
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
- 编写yml
点击查看详情
# 端口号
server:
port: 8080
spring:
application:
name: mybatisdemo
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.0.102:3306/mybatisdemo?characterEncoding=utf-8&serverTimezone=UTC
username: root
password: 123456
mvc:
view:
suffix: ".html"
# 开启驼峰命名自动映射
mybatis:
configuration:
map-underscore-to-camel-case: true
mapperLocations: classpath:mapper/*.xml # 映射xml文件
logging:
level:
com:
chnq:
mybatisdomo: debug
- 启动类添加注解
@MapperScan
点击查看详情
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.chnq.mybatisdemo.mapper")
public class MybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
}
}
-
创建数据库
-
编写配置类
MybatisPlusConfig
点击查看详情
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.chnq.mybatisdemo.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
- 编写实体类User
点击查看详情
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
@TableName("t_user")
public class User implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private Date birthday;
}
- 编写实体类Book
点击查看详情
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
@TableName("t_book")
public class Book implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String bookname;
private BigDecimal price; // 保留小数点后两位
private String author;
}
mybatis plus 环境搭建
- mapper
点击查看详情
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
- service
点击查看详情
public interface UserService extends IService<User> {
}
// 实现类
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Resource
private UserMapper userMapper;
}
- 控制器
点击查看详情
@Controller
public class UserController {
@Resource
UserService userService;
@Resource
UserMapper userMapper;
// 调用service层接口查询所有
@GetMapping("/getUsers")
@ResponseBody
public String getUserList(){
List<User> user = userService.list();
System.out.println(user);
return RespResult.success("获取成功!", user);
}
// 调用mapper层接口查询所有
@GetMapping("/getUsers2")
@ResponseBody
public String getUserTest(){
List<User> users = userMapper.selectList(null);
users.forEach(user-> System.out.println("user = " + user));
return RespResult.success("获取成功!", users);
}
// 调用mapper层接口查询单个
@GetMapping("/getUser")
@ResponseBody
public String testFindOne(@PathParam("id") int id){
User user = userMapper.selectById(id);
return RespResult.success("获取成功!", user);
}
// 调用mapper层接口添加数据
@GetMapping("/save")
@ResponseBody
public String testSave(){
User user = new User();
user.setUsername("小兰");
user.setPassword("123456");
userMapper.insert(user);
return RespResult.success("添加成功!", user);
}
}
- 测试一下
点击查看详情
-
在控制器中注入了service对象和mapper对象,就可以直接调用mybatis plus为我们提供的方法,
ctrl + f12
可查看方法
-
更过crud方法参考mybatis puls官网
-
使用注解自定义sql
参考
点击查看详情
// mapper层
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 使用注解自定义sql
@Select("select * from t_user")
List<User> getAll();
}
// 控制层
@Controller
public class UserController {
@Resource
UserMapper userMapper;
// 使用注解自定义sql
@GetMapping("/getAll")
@ResponseBody
public String getAll(){
List<User> users = userMapper.getAll();
System.out.println(users);
return RespResult.success("添加成功!", users);
}
}
使用xml自定义sql
参考
点击查看详情
// mapper
@Mapper
public interface BookMapper extends BaseMapper<Book> {
List<Book> getAll();
}
// xml,在resource路径下新建mapper文件夹,在该文件夹下编写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.chnq.mybatisdemo.mapper.BookMapper">
<select id="getAll" resultType="com.chnq.mybatisdemo.model.Book">
select id, bookname, price, author from t_book
</select>
</mapper>
// service
public interface BookService extends IService<Book> {
List<Book> getAll();
}
// 实现类
@Service
@Transactional
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
@Resource
private BookMapper bookMapper;
@Override
public List<Book> getAll() {
return bookMapper.getAll();
}
}
// controller
@RestController
@RequestMapping(value = {"/book"})
public class BookController {
@Resource
BookService bookService;
@RequestMapping(value = {"/getBooks"})
@ResponseBody
public String decrease() {
List<Book> books = new LinkedList<>();
books = bookService.getAll();
System.out.println(books);
return RespResult.success(books);
}
}
使用匿名内部类风格构造器自定义sql
参考
点击查看详情
// mapper层
@Mapper
public interface UserMapper extends BaseMapper<User> {
@UpdateProvider(type = UserProvider.class, method = "updateUser")
int updateUser(@Param("user") User user, @Param("id") int id);
class UserProvider {
public String updateUser(@Param("user") User user, @Param("id") int id) {
SQL sql = new SQL();
sql.UPDATE("t_user");
if(user.getUsername() != null) {
sql.SET("username=#{user.username}");
}
if(user.getPassword() != null) {
sql.SET("password = #{user.password}");
}
if(user.getBirthday() != null) {
sql.SET("birthday = #{user.birthday}");
}
sql.WHERE("id = #{id}");
return sql.toString();
}
}
}
// controller层
@Controller
public class UserController {
@Resource
UserMapper userMapper;
@GetMapping("/testUpdate")
@ResponseBody
public String testUpdate(@PathParam("id") int id){
User user = new User();
user.setUsername("cyq");
user.setPassword("123456");
userMapper.updateUser(user, id);
return RespResult.success("添加成功!", user);
}
}
使用Fluent风格自定义sql
参考
点击查看详情
// mapper层
@Mapper
public interface UserMapper extends BaseMapper<User> {
@SelectProvider(type = addUserProvider.class, method = "addUser")
Integer addUser(@Param("username") String username, @Param("password") String password, @Param("birthday") Date birthday);
class addUserProvider {
public String addUser(@Param("username") String username, @Param("password") String password, @Param("birthday") Date birthday) {
String sql = new SQL()
.INSERT_INTO("t_user")
.VALUES("username, password", "#{username}, #{password}")
.VALUES("birthday", "#{birthday}")
.toString();
return sql;
}
}
}
// controller层
@Controller
public class UserController {
@Resource
UserMapper userMapper;
@GetMapping("/testAdd")
@ResponseBody
public String testAdd(){
Date bir = new Date();
userMapper.addUser("chenx", "123456", bir);
return RespResult.success("添加成功!");
}
}
报错
- 错误描述:拉取依赖时报错
Cannot find file
- 错误原因:maven3.8.2的问题,切换为idea自带maven或安装maven3.6.1及其以下版本
- 参考
- 错误2:在控制层中调用mapper层的insert方法插入数据时报错:
java.lang.IllegalArgumentException: argument type mismatch
- 错误原因:实体类中属性的类型与数据库中字段类型不一致、实体类没有构造方法、MybatisPlus主键生成策略不匹配
- 参考
- 应该将实体类修改为如下
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
@TableName("t_user")
public class User implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private Date birthday;
}
- 使用Fluent风格自定义sql时报错:
attempted to return null from a method with a primitive return type (int)
- 解决方案:将mapper层的返回类型int改为Integer
- 参考