您好,登錄后才能下訂單哦!
這篇文章主要介紹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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。