In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the introduction of MyBatis-Plus and the introduction of basic operation". In the daily operation, I believe many people have doubts about the introduction of MyBatis-Plus and the introduction of basic operation. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "introduction of MyBatis-Plus and basic operation". Next, please follow the editor to study!
Catalogue
A brief introduction to MyBatis-Plus (from the official website)
Second, get started quickly
III. General CRUD
3.1 insert (insert operation)
3.2 updateById (update operation)
3. 3 query operations-various select
3.4 Delete operations-various delete
Add 1: if the name of the table or the name of the attribute in the table is different from the name of our entity class
A brief introduction to MyBatis-Plus (from the official website)
MyBatis-Plus, referred to as MP, is an enhancement tool of MyBatis, which is only enhanced but not modified on the basis of MyBatis, in order to simplify development and improve efficiency.
Properties:
Non-intrusive: only enhancements are made without changes, and the introduction of it will not affect existing projects and is as smooth as silk
Low loss: basic CURD will be automatically injected at startup, performance is basically lossless, and direct object-oriented operation
Powerful CRUD operations: built-in general Mapper, general Service, you can achieve a single table only through a small number of configurations-most CRUD operations, more powerful conditional constructors to meet all kinds of use needs
Support for Lambda calls: through Lambda expressions, it is convenient to write all kinds of query conditions without having to worry about field errors
Support for automatic primary key generation: support up to 4 primary key strategies (including distributed unique ID generator-Sequence), which can be freely configured to solve the primary key problem perfectly.
Support ActiveRecord mode: support ActiveRecord form calls, entity classes only need to inherit the Model class to carry out powerful CRUD operations
Support custom global general operations: support global general method injection (Write once, use anywhere)
Built-in code generator: use code or Maven plug-ins to quickly generate Mapper, Model, Service, Controller layer code, support template engine, and have more custom configurations for you to use.
Built-in paging plug-in: based on MyBatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query.
The paging plug-in supports multiple databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
Built-in performance analysis plug-in: it can output SQL statements and its execution time. It is recommended to enable this function when developing tests, which can quickly find out slow queries.
Built-in global intercept plug-in: provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation.
Second, get started quickly
Step 1. Create a new database table and write the corresponding JavaBean class.
First of all, let's use the student table built by Mybatis before. (here, I removed the s _ in front of the names of the four attributes.)
Then create a Bean for our table.
Package com.example.po;public class Student {private Integer id; private String name; private String email; private Integer age; public Student () {} public Student (Integer id, String name, String email, Integer age) {this.id = id; this.name = name; this.email = email; this.age = age;} public Integer getId () {return id } public void setId (Integer id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name;} public String getEmail () {return email;} public void setEmail (String email) {this.email = email;} public Integer getAge () {return age } public void setAge (Integer age) {this.age = age;} @ Override public String toString () {return "Student {" + "id=" + id + ", name='" + name +'\'+ ", email='" + email +'\'+ ", age=" + age +'}' }}
Step 2. Add dependencies
Mybatis and mybatis-plus automatically maintain our mybatis and mybatis-spring-related dependencies
Com.baomidou mybatis-plus 3.4.3 junit junit 4.13.1 test log4j log4j 1.2.17 com.mchange C3p0 0.9.5.2 mysql mysql-connector-java 8.0.26 org.springframework spring-context 5.3.9 org.springframework spring-orm 5.3.9
Step 3. Write the configuration file
Configuration file for mybatis:
Mybatis-config.xml
Log4j.xml log
Db.properties
Jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost/mybatis?useSSL=false&serverTimezone=UTCjdbc.username=rootjdbc.password=root
ApplicationContext.xml
Step 4. Integrate MP (Mybatis-Plus, later referred to as MP)
The integration of MP is very simple. For Spring, we just need to replace the MyBatisSqlSessionFactory that comes with Mybatis with that that comes with MP. This is the paragraph in the applicationContext.xml file:
If it is Mybatis, then the value of class is org.mybatis.spring.SqlSessionFactoryBean
III. General CRUD
Now that we are ready, we can start our CRUD. (it's starting to feel good)
First of all, let's talk about what we did with mybatis before:
Steps:
1. Create dao API
2. Write interface method
3. Create a mapper file and write sql statements for each interface method
4. Register mapper in the main configuration file of mybatis
Then let's talk about what MP does:
Steps:
1. Create the dao API, inherit the BaseMapper API, and pass in its corresponding entity class.
It's gone?! Yes, this is the only one. There is no need to write our xml file. MP has written it all for us. Let's write the test code directly:
3.1 insert (insert operation) package com.example.text;import com.example.dao.StudentDao;import com.example.po.Student;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {private ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml"); private StudentDao studentDao = context.getBean ("studentDao", StudentDao.class) / / generic insert operation @ Test public void testInsert () {/ / initialize Student Student student = new Student (null, "Lin Ba", "linba@163.com", 23); int num = studentDao.insert (student); System.out.println ("successfully added" + num+ "records");}}
After execution, look at our database (added successfully)
After insertion, we can even directly get the self-increasing id value as follows:
@ Test public void testInsert () {/ / initialize Student Student student = new Student (null, "Zhang Fei", "liubei@163.com", 30); int num = studentDao.insert (student); System.out.println ("successfully add" + num+ "record"); / / after the insert operation is executed, we can get the self-increasing primary key value int id = student.getId () System.out.println ("inserted primary key value is:" + id);}
Database:
Console:
3.2 updateById (update operation)
Just pass in a Student object. (all values except id can be empty, and empty fields will not appear in the sql statement.)
Write the test method directly:
/ / General update operation @ Test public void testUpdateById () {/ / initialize Student Student student = new Student (1004, "Guan Yu", "guanyu@qq.com", 29); int result = studentDao.updateById (student); System.out.println ("successfully modified" + result+ "records");}
Database:
3. 3 query operations-various select
Query via id: selectById
Test public void testSelectById () {Student student = studentDao.selectById (1007); System.out.println (student);}
Display:
Use and to query a single record: selectOne (error will be reported if plural records are returned)
@ Test public void testSelectOne () {/ / write an anonymous class and set the entity class Wrapper stu = new Wrapper () {@ Override public Student getEntity () {return new Student (null, "Guan Yu", null,29) of the combination condition we want to query } @ Override public MergeSegments get_Expression () {return null;} @ Override public void clear () {} @ Override public String getSqlSegment () {return null;}} Student student = studentDao.selectOne (stu); System.out.println (student);}
Results:
Use in to query multiple records with id values (selectBatchIds)
@ Test public void testSelectBatchIds () {List ids = new ArrayList (); ids.add (1001); ids.add (1002); List students = studentDao.selectBatchIds (ids); for (Student stu:students) {System.out.println (stu);}}
Display:
Input Map to query several pieces of data through and: selectByMap
@ Test public void testSelectByMap () {Map map = new HashMap (); / / the key of map must be the same as the column name in the table map.put ("s_name", "Zhang Fei"); map.put ("s_age", 28); List students = studentDao.selectByMap (map); for (Student stu:students) {System.out.println (stu);}}
Results:
3.4 Delete operations-various delete
Delete records through id: deleteById
Delete multiple records through multiple id: deleteBatchIds
Delete records through and combination condition: deleteByMap
@ Test public void testDeleteById () {int result = studentDao.deleteById (1001); System.out.println ("successfully deleted" + result+ "records");} @ Test public void testDeleteBatchIds () {List ids = new ArrayList (); ids.add (1002); ids.add (1003); int result = studentDao.deleteBatchIds (ids) System.out.println ("successfully deleted" + result+ "records");} @ Test public void testDeleteByMap () {Map map = new HashMap (); map.put ("s_id", 1005); map.put ("s_name", "Liu Qi"); int result = studentDao.deleteByMap (map); System.out.println ("successfully deleted" + result+ "records");}
Execute the above method in turn, and the console and database display:
Add 1: if the name of the table or the name of the attribute in the table is different from the name of our entity class
If now, our table name is mp_student.
The name of the attribute is saccounidrechedomery, respectively, and the name of the attribute is slightnamerecoveryemailrecoverage.
So, we're going to be in the entity class
1. Annotate entity classes with @ TableName
2. Use @ IdName to mark the primary key
3. Use @ TableField to mark non-primary keys
As follows:
Package com.example.po;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableId;import com.baomidou.mybatisplus.annotation.TableName @ TableName (value = "mp_student") public class Student {/ * * TableId Mark this is the primary key * value value tells MP the property name of the primary key in the table (the same can also be omitted) * type values have the following Respectively: * AUTO database ID self-increment * NONE stateless, this type is not set primary key type (global equals global, global Rio equals INPUT) * set primary key value before INPUT insert * ASSIGN_ID assigns ID (primary key type is Number (Long and Integer) or String) (since 3.3.0) Use interface IdentifierGenerator's method nextId (default implementation class is DefaultIdentifierGenerator snowflake algorithm) * ASSIGN_UUID assign UUID, primary key type is String (since 3.3.0), and use interface IdentifierGenerator's method nextUUID (default default method) * * / @ TableId (value = "s_id", type = IdType.AUTO) private Integer id TableField (value = "s_name") private String name; @ TableField (value = "s_email") private String email; @ TableField (value = "s_age") private Integer age; public Student () {} public Student (Integer id, String name, String email, Integer age) {this.id = id; this.name = name; this.email = email; this.age = age } public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name;} public String getEmail () {return email;} public void setEmail (String email) {this.email = email } public Integer getAge () {return age;} public void setAge (Integer age) {this.age = age } @ Override public String toString () {return "Student {" + "id=" + id + ", name='" + name +'\'+ ", email='" + email +'\'+ ", age=" + age +'}';}}
Note: if you set the type=AUTO of the primary key, you must set the self-increment of the primary key in the database and set the starting value of self-increment. The settings are as follows:
Select your own database table and click Design Table
Select the primary key and click the Auto Increment below (self-increment)
Click the Option menu item to set the starting value of self-increment.
At this point, the study of "introduction to MyBatis-Plus and introduction to basic operation" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.