Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use MyBatis-Plus to operate Database in Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use MyBatis-Plus to operate the database in Java. It is very detailed and has certain reference value. Friends who are interested must finish reading it.

MyBatis-Plus

MyBatis-Plus (opens new window) (MP for short) is an enhancement tool of MyBatis (opens new window), which is only enhanced but not changed on the basis of MyBatis, in order to simplify development and improve efficiency.

MyBatis can manipulate the database directly through SQL statements in xml, which is very flexible. But all its operations are carried out through SQL statements, so it is troublesome to write a large number of xml files. Mybatis-plus solves this problem very well.

Official website

MyBatis-Plus official documentation

Use

The database I use here is mysql8, create a new test database, and create a user table

Construction table sentence

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 'key', `name` varchar (20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'name', `age`int (0) NULL DEFAULT NULL COMMENT 'age', `address`varchar (50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'address', PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1

Introduce dependency

The database I use here is 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

Create application.yml and application-dev.yml files respectively

Application.yml

# Spring configuration spring: # Environment Settings profiles: active: dev # template engine thymeleaf: mode: HTML encoding: utf-8 # disable caching cache: false # Service Module devtools: restart: # Hot deployment switch enabled: true

Application-dev.yml

# Development environment configuration server: # HTTP port of server The default is 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

Write the entity class User.java, which uses lombok

@ Datapublic class User {private String id; private String name; private Integer age; private String address;}

Create a mapper folder and write the Mapper class UserMapper.java

Public interface UserMapper extends BaseMapper {}

Add the @ MapperScan annotation to the Spring Boot startup class and scan the Mapper folder:

@ SpringBootApplication@MapperScan ("com.mybatisplus.mapper") public class MainApplication {public static void main (String [] args) {SpringApplication.run (MainApplication.class, args);}}

Add a test class for functional testing:

The test data is inserted into the database @ Autowired private UserMapper userMapper; @ Test public void testInsert () {System.out.println (("- insert method test -")); User user = new User (); / / the primary key is generated automatically, such as 550E8400-E29B-11D4-A716-446655440000 String id = UUID.randomUUID () .toString () String replaceAll = id.replaceAll ("-", "); / / 550E8400E29B11D4A716446655440000 user.setId (replaceAll); user.setName (" Zhang San "); user.setAge (21); user.setAddress (" Haidian District of Beijing "); int insert = userMapper.insert (user); if (insert > 0) {System.out.println (" insert success: "+ user) } else {System.out.println ("insert failed!") ;}}

Test query all @ Autowired private UserMapper userMapper; @ Test public void testSelect () {System.out.println (("- selectAll method test -")); List userList = userMapper.selectList (null); userList.forEach (System.out::println);}

Test delete data

Delete the record whose name is equal to "Zhang San"

@ Autowired private UserMapper userMapper; @ Test public void testDelete () {System.out.println (("- delete method test -")); LambdaQueryWrapper wrapper = new LambdaQueryWrapper (); User user = new User (); user.setName ("Zhang San"); wrapper.eq (User::getName, user.getName ()); int delete = userMapper.delete (wrapper) If (delete > 0) {System.out.println ("deletion succeeded:" + user);} else {System.out.println ("deletion failed!") ;}}

Test modified data

Perform the next insert before modification

You can also use the userMapper.updateById (T entity) method to modify it, passing in an entity class

@ Autowired private UserMapper userMapper; @ Test public void testUpdate () {System.out.println (("- update method test -")); LambdaQueryWrapper wrapper = new LambdaQueryWrapper (); User user = new User (); user.setName ("Zhang San"); wrapper.eq (User::getName, user.getName ()); User userNew = new User () UserNew.setName ("Li Si"); int update = userMapper.update (userNew, wrapper); if (update > 0) {System.out.println ("modified successfully:" + user);} else {System.out.println ("modify failed!") ;}}

The above is all the contents of the article "how to use MyBatis-Plus to operate database in Java". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report