Mybatis plus案例
前言
- 当表名为user时,会多生成2个实体类
- 正常情况下生成的类
- 测试是否可以直接在当前
mybatis代码生成器的项目
中开发
- 启动项目后测试,发现当前项目只能用来生成代码
- 即使项目添加所需的开发依赖,启动项目后依然无法找到接口
path
,或者报依赖冲突的错误
- 解决方案,参考
gitee/chnx/cloud/seata/seata01
项目重新构建一个项目,将生成的代码复制到新项目中 案例要求
# 使用代码生成器生成代码
# 工具类:返回对象工具类、分页对象工具类
# 使用分页、分页连接查询
# 传入参数为对象、集合、集合对象
案例一
使用mybatis代码生成器生成代码
- 使用的
mybatis代码生成器项目案例
是gitee/chenx/mybatis-geneator - 未使用该方式开发的原因:
# 在该代码生成器项目中生成代码后,无法直接在该项目上继续开发
# 将生成的代码复制到1个新建的项目,需修改每个类的路径,已经违背了使用代码生成器的初衷
案例二
- 案例地址
使用mybatis plus代码生成器生成代码
- 首先参考
案例二
生成代码 - 生成代码后,将pom.xml中的依赖删除,将application.properties中的配置删除,并重命名为application.yml
- 注释掉
测试类
中的main方法 - 之后参考构建mybatis plus项目
- 将maven配置为3.6.1或IDE自带的maven,否者某些依赖无法导入
- 导入如下依赖
点击查看详情
<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>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</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.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>
<!-- 以下为代码生成器中的依赖 -->
<!-- freemarker模板和velocity模板依赖,后面配置的时候会2选其1 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.20</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: mybatisplus
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.0.102:3306/dbtest?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
logging:
level:
com:
chnq:
mybatisplus: debug
- 配置启动类
点击查看详情
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.chnq.mybatisplus.mapper")
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
- 编写mybatis plus 配置类
点击查看详情
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;
}
}
- 检查实体类中的
注解配置
- 检查mapper层注解
- 检查service层注解,并注入mapper
- 检查controller层注解,并注入mapper、service
- 在controller层调用mapper对象和service对象中的方法进行测试
点击查看详情
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
UserService userService;
@Resource
UserMapper userMapper;
// 测试
// 调用service层接口查询所有
@GetMapping("/getUsers")
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);
}
}
-
在service层和controller层注入对象时,
无法注入
,是因为之前使用代码生成器的依赖被删除了,之后重新配置了mybatis plus开发所需的依赖,导致还有缓存 -
解决方案参考
-
配置工具类
-
编写req
点击查看详情
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
public class UserBookReq implements Serializable {
private static final long serialVersionUID = 1L;
// 用户名
private String username;
// 性别
private String sex;
// 书名
private String bookname;
// 作者
private String author;
// 价格
private BigDecimal price;
// 当前页
private int pageNum = 1;
// 每页条数
private int pageSize = 5;
}
编写resp
点击查看详情
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class UserBookResp implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uId;
private String username;
private String password;
private String sex;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;
private Integer bId;
private String bookname;
private String author;
private BigDecimal price;
}
编写mapper
点击查看详情
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 连接查询
List<User> findUser();
// 分页查询
List<User> findUsers();
// 分页连接查询
List<UserBookResp> getUserBook(UserBookReq userBookReq);
}
编写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.mybatisplus.mapper.UserMapper">
<!-- 连接查询 -->
<select id="findUser" resultType="com.chnq.mybatisplus.entity.User">
select u.id, u.username, u.password, u.sex, u.birthday, b.id, b.bookname, b.author, b.price from user u inner join book b on u.username = b.author;
</select>
<!-- 连接查询:第3条开始的3条数据 -->
<select id="findUsers" resultType="com.chnq.mybatisplus.entity.User">
SELECT * FROM user LIMIT 2,3;
</select>
<!-- 分页连接查询 -->
<select id="getUserBook" resultType="com.chnq.mybatisplus.resp.UserBookResp">
select u.id, u.username, u.password, u.sex, u.birthday, b.id, b.bookname, b.author, b.price
from user u inner join book b on u.username = b.author
where
<if test="username != null">
u.username = #{username}
</if>
<if test="sex != null">
or u.sex = #{sex}
</if>
<if test="bookname != null">
or b.bookname = #{bookname}
</if>
<if test="author != null">
or b.author = #{author}
</if>
<if test="price != null">
or b.price = #{price}
</if>
<if test="pageNum !=null and pageSize != null">
limit #{pageNum}, #{pageSize}
</if>
</select>
</mapper>
编写service
点击查看详情
public interface UserService extends IService<User> {
// 连接查询
List<User> findUser();
// 分页查询
List<User> findUsers();
// 分页连接查询
List<UserBookResp> getUserBook(UserBookReq userBookReq);
}
编写service实现类
点击查看详情
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Resource
private UserMapper userMapper;
@Override
public List<User> findUser() {
return userMapper.findUser();
}
@Override
public List<User> findUsers() {
return userMapper.findUsers();
}
@Override
public List<UserBookResp> getUserBook(UserBookReq userBookReq) {
return userMapper.getUserBook(userBookReq);
}
}
编写controller
点击查看详情
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
UserMapper userMapper;
// 连接查询
@GetMapping("/userList")
@ResponseBody
public String UserList(){
List<User> users = userMapper.findUser();
users.forEach(user-> System.out.println("user = " + user));
return RespResult.success("获取成功!", users);
}
// 分页查询
@GetMapping("/usersList")
@ResponseBody
public String UsersList(){
List<User> users = userMapper.findUsers();
users.forEach(user-> System.out.println("user = " + user));
return RespResult.success("获取成功!", users);
}
// 分页连接查询
@RequestMapping(value = "/listAll", method = RequestMethod.POST)
public List<UserBookResp> listAll(@RequestBody UserBookReq req){
return userService.getUserBook(req);
}
}
- 测试