这篇文章主要介绍Java中如何使用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 '地址', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
引入依赖
这里我用的数据库是mysql8
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.3</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </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-test</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <!--Druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> </dependencies>
分别创建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<User> { }
在 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<User> userList = userMapper.selectList(null); userList.forEach(System.out::println); }
删除姓名等于“张三”的记录
@Autowired private UserMapper userMapper; @Test public void testDelete() { System.out.println(("----- delete method test ------")); LambdaQueryWrapper<User> 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<User> 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("修改失败!"); } }
以上是“Java中如何使用MyBatis-Plus操作数据库”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。