SpringBoot整合mybatis-plus

mybatis-plus自带了mybatis,所以不用重复导入了

为什么使用mybatis-plus:

Mybatis-Plus查单表比较方便,而且还写好了常用的的查询语句,可以直接使用

创建数据库:

CREATE DATABASE `security` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

创建表:

CREATE TABLE user  (
  id int unsigned auto_increment,
  username varchar(32) NOT NULL,
  password varchar(32) NOT NULL,
  PRIMARY KEY (id)
);

插入表数据:

insert into user(id,username,password) values('1','root','root');
insert into user(id,username,password) values('2','admin','admin');
insert into user(id,username,password) values('3','jack','123456');

查询表:

select * from user;

SpringBoot 连接MySql配置 JDBC5:

导入Jar包,SpringBoot3.0 以下:

<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>
<!--mybatis-plus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>

 application.properties连接MySql数据库配置:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_name?useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

entity层:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j

// mybatis-plus
@TableName(value = "user")
public class User {

    // IdType.ASSIGN_ID 雪花算法
    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private String id;

    // exist = true 数据表中存在该字段
    @TableField(value = "username", exist = true)
    // 非空约束
    @NonNull
    private String username;

    @TableField(value = "password", exist = true)
    @NonNull
    private String password;
    // 传给前端的日期格式
    @JsonFormat(pattern = "yyyy年MM月dd日 HH:mm:ss",timezone="Asia/Shanghai")
    private Date createTime;

}

Dao层:

@Mapper
public interface UserDao extends BaseMapper<User> {}

Service层:

@Service
public class UserServiceImpl {
    
    @Autowired
    UserDao userDao;
    
}

使用测试类进行测试:

@Test
public void testInsertUser() {

    userService.addUser(new User(null, "lisi", "123456"));

}

controller层:

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @PostMapping()
    public String addUser(HttpServletRequest request, User user) {

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {

        } else {

        }

        if (userService.findUser(user.getUsername()) != null) {
            return Result.failGetString("用户名已存在");
        } else {
            int result = userService.addUser(user);
            return Result.okGetString("插入成功",user);
        }

    }

    @DeleteMapping()
    public String delUser(HttpServletRequest request, User user) {

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {

        } else {

        }

        String message = userService.delUserById(user.getId());

        if (message.equals("1")) {
            return Result.okGetString("删除成功",user);
        } else if (message.equals("0")) {
            return Result.failGetString("删除失败 原因:没有找到该用户的编号");
        } else {
            return Result.failGetString("删除失败");
        }

    }

    @PutMapping()
    public String updateUser(HttpServletRequest request, User user) {

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {

        } else {

        }

        int message = userService.updateUserById(user);

        if (message == 1) {
            return Result.okGetString("更新成功",user);
        } else {
            return Result.failGetString("更新失败");
        }

    }
}

后端返回的模板:

{
	"code": 0,
    "msg": "success",
	"data": {
		"token":                                                                                                             "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2JpbGUiOiIxODI4OTQ1NDg0NiIsInZlcl9jb2RlIjoi8J6Jg                        CIsImV4cCI6MTY4NTMzMDk4OCwiaXNzIjoicHJvOTExIn0.zb_ZL6JohYkHdUwQp7678SqiwFpuxpBhBtdsS7L1k1w",
        "name":"张三",
        "age":36
	}
}

在test/com/cy/store/StoreApplicationTests.java下编写测试类,查看MySql是否连接成功:

@Test
void getConnection() throws SQLException {
    Connection connection = dataSource.getConnection();
    System.out.println("connection=" + connection);
    // HikariProxyConnection 默认连接池
}

mybatis-plus的逻辑删除:

mybatis-plus.global-config.db-config.logic-delete-field=is_delete
mybatis-plus.global-config.db-config.logic-not-delete-value=0
mybatis-plus.global-config.db-config.logic-delete-value=1
# id自增
mybatis-plus.global-config.db-config.id-type=auto

开启debug日志:

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

开启分页查询的total的配置类:

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mpi = new MybatisPlusInterceptor();
        mpi.addInnerInterceptor(new PaginationInnerInterceptor());
        return mpi;
    }
}

分页查询的案例:

@Override
public ResponseResult hotArticleList() {
    // 条件
    LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Article::getStatus, 0);
    wrapper.orderByDesc(Article::getViewCount);
    // 分页
    Page<Article> page = new Page<>(0, 10);
    // 结果
    Page<Article> result = page(page, wrapper);
    return ResponseResult.success(result);
}

分页查询,开启total/count目标行数: 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋劲豪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值