Java中使用MyBatis

网友投稿 250 2022-08-30


Java中使用MyBatis

目录MyBatis-Plus官网使用测试数据插入数据库 测试查询所有 测试删除数据 测试修改数据

MyBatis-Plus

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

MyBatis可以直接在xml中通过SQL语句操作数据库,很灵活。但其操作都要通过SQL语句进行,就必须写大量的xml文件,很麻烦。mybatis-plus就很好的解决了这个问题。

官网

MyBatis-Plus 官方文档

使用

这里我用的数据库是mysql8,新建test数据库,并创建user表

建表语句

SET NAMES utf8mb4;

SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------

-- Table structure for user

-- ----------------------------

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (

`id` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键',

`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',

`age` int(0) NULL DEFAULT NULL COMMENT '年龄',

`address` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地址',

PRIMARtvatuuY KEY (`id`) USING BTREE

) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

引入依赖

这里我用的数据库是mysql8

org.springframework.boot

spring-boot-starter-parent

2.6.3

org.projectlombok

lombok

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-devtools

runtime

true

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-test

junit

junit

org.springframework

spring-test

com.baomidou

mybatis-plus-boot-starter

3.5.1

com.alibaba

druid-spring-boot-starter

1.1.9

mysql

mysql-connector-java

8.0.25

分别创建application.yml及application-dev.yml文件

application.yml

# Spring配置

spring:

# 环境设置

profiles:

active: dev

# 模板引擎

thymeleaf:

mode: HTML

encoding: utf-8

# 禁用缓存

cache: false

# 服务模块

devtools:

restart:

# 热部署开关

enabled: true

application-dev.yml

# 开发环境配置

server:

# 服务器的HTTP端口,默认为80

port: 8081

spring:

datasource:

type: com.alibaba.druid.pool.DruidDataSource

driver-class-name: com.mysql.cj.jdbc.Driver

druid:

url: jdbc:mysql://localhost:3307/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8

username: root

password: 123456

initial-size: 5

min-idle: 10

max-active: 20

max-wait: 60000

time-between-eviction-runs-millis: 60000

min-evictable-idle-time-millis: 300000

validation-query: select 'x'

test-while-idle: true

test-on-borrow: false

test-on-return: false

pool-prepared-statements: true

max-open-prepared-statements: 50

max-pool-prepared-statement-per-connection-size: 20

编写实体类User.java,这里用到lombok

@Data

public class User {

private String id;

private String name;

private Integer age;

private String address;

}

创建mapper文件夹,并编写 Mapper 类 UserMapper.java

public interface UserMapper extends BaseMapper {

}

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

@SpringBootApplication

@MapperScan("com.mybatisplus.mapper")

public class MainApplication {

public static void main(String[] args)

{

SpringApplication.run(MainApplication.class, args);

}

}

添加测试类,进行功能测试:

测试数据插入数据库

@Autowired

private UserMapper userMapper;

@Test

public void testInsert() {

System.out.println(("----- insert method test ------"));

User user = new User();

// 自动生成主键,例如550E8400-E29B-11D4-A716-446655440000

String id = UUID.randomUUID().toString();

String replaceAll = id.replaceAll("-", "");

//550E8400E29B11D4A716446655440000

user.setId(replaceAll);

user.setName("张三");

user.setAge(21);

user.setAddress("北京市海淀区");

int insert = userMapper.insert(user);

if(insert>0){

System.out.println("插入成功:"+user);

}else{

System.out.println("插入失败!");

}

}

测试查询所有

@Autowired

private UserMapper userMapper;

@Test

public void testSelect() {

System.out.println(("----- selectAll method test ------"));

List userList = userMapper.selectList(null);

userList.forEach(System.out::println);

}

测试删除数据

删除姓名等于“张三”的记录

@Autowired

private UserMapper userMapper;

@Test

public void testDelete() {

System.out.println(("----- delete method test ------"));

LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();

User user = new User();

user.setName("张三");

wrapper.eq(User::getName, user.getName());

int delete = userMapper.delete(wrapper);

if(delete>0){

System.out.println("删除成功:"+user);

}else{

System.out.println("删除失败!");

}

}

测试修改数据

修改前先执行下插入

修改还可以用userMapper.updateById(T entity)方法来修改,传入一个实体类

@Autowired

private UserMapper userMapper;

@Test

public void testUpdate() {

System.out.println(("----- update method test ------"));

LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();

User user = new User();

user.setName("张三");

wrapper.eq(User::getName, user.getName());

User userNew = new User();

userNew.setName("李四");

int update = userMapper.update(userNew, wrapper);

if(update>0){

System.out.println("修改成功:"+user);

}else{

System.out.println("修改失败!");

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python第三方库安装只需掌握这一种就够啦(Python如何安装第三方库)
下一篇:我用千行代码做了python版AI五子棋?还真玩不过AI了!!(python编写五子棋)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~