当前位置:网站首页>MP framework basic operation (self use)
MP framework basic operation (self use)
2022-06-11 00:14:00 【m0_ sixty-one million four hundred and ninety-nine thousand thr】
Catalog
Set the field mapping relationship
Custom method (mapper Interface )
Get ready Pagination plug-in unit
In front of Conditions
rely on
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Configuration information yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mp_db?characterEncoding=utf-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
Start class
@SpringBootApplication
@MapperScan("com.mapper")
public class SGApplication {
public static void main(String[] args) {
SpringApplication.run(SGApplication.class);
}
}
mapping problem
The rules Table name
You can add... To the class name of the entity class @TableName Note to identify
If the table name is tb_user, The entity class name is User You can use the following expression .
@TableName("tb_user")
public class User {
//....
}The rules Primary key
for example :
If you want to set the automatic growth of the primary key, you can set it as follows
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private Long id;
//.....
}
AUTO
database ID Self increasing , Database dependent . Please make sure that the database is set with ID Self increasing Otherwise it will not work
NONE
The primary key type is not set . If the primary key is not set manually in the code , It will be automatically generated according to the global policy of the primary key ( The default global primary key policy is self incrementing based on snowflake algorithm ID)
INPUT
You need to set the primary key manually , If we do not set up . Insert operation generates SQL When the sentence is , The value of the primary key column will be null.
ASSIGN_ID
When the primary key is not set manually , That is, when the primary key attribute in the entity class is empty , Will automatically fill , Use snowflake algorithm
ASSIGN_UUID
When the primary key attribute of the entity class is empty , Will automatically fill , Use UUID
Set the field mapping relationship
If a column in the table is called address and The attribute in the entity class is named addressStr You can use the following methods to configure .
@TableField("address")
private String addressStr;MP in Default hump naming ,userName --- user_name( In the database )
Based on using
Basic query No, Conditions
XXXXXMapper.selectList(null)add to
Domain domain =new domain();
domain.set Field ("");
XXmapper.insert(domain)Delete
1 direct according to id Delete
XXmapper.deteteByid(X);
2 establish Array Delete
List<Integer> ids = new ArrayList<>();
ids.add(5);
ids.add(6);
ids.add(7);
int i = userMapper.deleteBatchIds(ids);
System.out.println(i);
Map<String, Object> map = new HashMap<>();
map.put("name"," Tim ");
map.put("age",22);
int i = userMapper.deleteByMap(map);
System.out.println(i);
}
modify
domain do = new domaim();
do.setid();
do.set Field ();
mapper.update(do)Condition selector

QueryWrapper
Common conditions
eq:equals, be equal to
gt:greater than , Greater than >
ge:greater than or equals, Greater than or equal to ≥
lt:less than, Less than <
le:less than or equals, Less than or equal to ≤
between: amount to SQL Medium BETWEEN
like: Fuzzy matching .like(“name”,“ yellow ”), amount to SQL Of name like ‘% yellow %’
likeRight: Fuzzy match right half .likeRight(“name”,“ yellow ”), amount to SQL Of name like ‘ yellow %’
likeLeft: Fuzzy match left half .likeLeft(“name”,“ yellow ”), amount to SQL Of name like ‘% yellow ’
notLike:notLike(“name”,“ yellow ”), amount to SQL Of name not like ‘% yellow %’
isNull
isNotNull
and:SQL Connector AND
or:SQL Connector OR
in: in(“age",{1,2,3}) amount to age in(1,2,3)
groupBy: groupBy(“id”,“name”) amount to group by id,name
orderByAsc :orderByAsc(“id”,“name”) amount to order by id ASC,name ASC
orderByDesc :orderByDesc (“id”,“name”) amount to order by id DESC,name DESC
Basic use
QueryWrapper wrapper = new QueryWrapper();
wrapper.gt("XXX",XX);
wrapper.eq("address"," Fox mountain ");
List<XXX> XXXX = XXXMapper.selectList(wrapper);
UpdateWrapper
Basic use
UpdateWrapper<XXX> updateWrapper = new UpdateWrapper<>();
updateWrapper.gt("id",1); Updated scope
updateWrapper.set("age",99); Modified data
XXXXMapper.update(null,updateWrapper);
Custom method (mapper Interface )
public interface UserMapper extends BaseMapper<User> {
User findMyUser(Long id);
}
XML Corresponding
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sangeng.mapper.UserMapper">
<select id="findMyUser" resultType="com.sangeng.domian.User">
select * from user where id = #{id}
</select>
</mapper>
Paging query
Get ready Pagination plug-in unit
@Configuration
public class PageConfig {
/**
* 3.4.0 Previous version
* @return
*/
/* @Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}*/
/**
* 3.4.0 After the version
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
Single table query
public void testPage(){
IPage<XXX> page = new Page<>();
// Set number of entries per page
page.setSize(2);
// Set the page number of the query
page.setCurrent(1);
userMapper.selectPage(page, null);
System.out.println(page.getRecords());// Gets the data of the current page
System.out.println(page.getTotal());// Get the total number of records
System.out.println(page.getCurrent());// The current page number
}Multi-table query
Inquire about A B Two form Of When
Add up Use mapper in Corresponding Entity class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Orders {
// Omit irrelevant code
private String userName;
} IPage<XXX> findAllOrders(Page<XXXX> XXXX);
public void testOrdersPage(){
Page<Orders> page = new Page<>();
// Set the size of each page
page.setSize(2);
// Set the current page number
page.setCurrent(2);
ordersMapper.findAllOrders(page);
System.out.println(page.getRecords());
System.out.println(page.getTotal());
}
Service
Before transformation
public interface UserService {
List<User> list();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> list() {
return userMapper.selectList(null);
}
}
After transformation
Compared with before Interface Will bring some methods , Basic query addition, deletion, modification and query can be completed by directly calling the interface .
public interface UserService extends IService<User> {
}@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
}
@Autowired
private UserService userService;
@Test
public void testSeervice(){
List<User> list = userService.list();
System.out.println(list);
}
Custom method
Comparison mapper Interface , There's no difference
public interface UserService extends IService<User> {
User test();
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
@Autowired
private OrdersMapper ordersMapper;
@Override
public User test() {
UserMapper userMapper = getBaseMapper();
List<Orders> orders = ordersMapper.selectList(null);
User user = userMapper.selectById(3);
// Query the user's order
QueryWrapper<Orders> wrapper = new QueryWrapper<>();
wrapper.eq("user_id",3);
List<Orders> ordersList = ordersMapper.selectList(wrapper);
return user;
}
}
Auto fill
Use tablefield(fill = fiedfill.insert_update)
/**
* Update time
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* Creation time
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
Custom fill processor MetaObjectHandler
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
// " Field ", data type ,value
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
}
}
Logical deletion
To configure
yml
mybatis-plus:
global-config:
db-config:
logic-delete-field: delFlag # The name of the entity field for global logical deletion (since 3.3.0, After configuration, you can ignore the non configuration steps 2)
logic-delete-value: 1 # Logical deleted value ( The default is 1)
logic-not-delete-value: 0 # Logical undeleted value ( The default is 0)
After deleting delflag Of The default value is Will change
result

边栏推荐
- 【Pygame小遊戲】別找了,休閑遊戲專題來了丨泡泡龍小程序——休閑遊戲研發推薦
- phpstudy的安装
- C language file operation
- 静态方法static学习
- [pyGame games] here it is. This Gobang game is super A. share it with your friends~
- 【漫天烟花】绚烂烟花点亮夜空也太美了叭、某程序员携带烟花秀给大家拜年啦~
- 【Pygame小游戏】别找了,休闲游戏专题来了丨泡泡龙小程序——休闲游戏研发推荐
- Qt客户端套接字QTcpSocket通过bind指定本地ip
- mybaits merge into
- MySQL命令行导入导出数据
猜你喜欢

第一章 总论-会计基础

博文推荐|构建 IoT 应用——FLiP 技术栈简介

Error report of curl import postman
![[pyGame games] story stream recommendation: what kind of games can you like? (devil lover, bully's wife version)](/img/77/653968895434f805d81a10406dcf6f.png)
[pyGame games] story stream recommendation: what kind of games can you like? (devil lover, bully's wife version)
![[untitled]](/img/7e/aab9560ef5a1b93f737a82561ec114.png)
[untitled]

Bluetooth development (8) -- avdtp connection process

Bluetooth development (3) -- look at the air bag

【Opencv实战】寒冷的冬季,也会迎来漫天彩虹,这特效你爱了嘛?

Why is the website snapshot hijacked and tampered with
![[turtle confessions collection]](/img/81/b4bacc23691e58e403f1330d0ca7cf.jpg)
[turtle confessions collection] "the moon at the bottom of the sea is the moon in the sky, and the person in front of us is the sweetheart." Be happy for the rest of your life, and be safe for ever ~
随机推荐
【AcWing】4. Multiple knapsack problem I
VTK例子--三個相交的平面
[database] MySQL index interview questions
Bluetooth development (7) -- L2CAP layer connection process
Qt客户端套接字QTcpSocket通过bind指定本地ip
安全生产月,黄埔开展燃气安全进商铺宣传活动
Bluetooth (5) -- about retransmission
Njupt South Post collection_ Experiment 1
启牛学堂理财可靠吗,安全吗
【Pygame小游戏】“史上最炫酷贪吃蛇”驾到,FUN开玩(不好玩不要钱)
SQL statement -- enter the month, query the date (month, year, day), and output the month
Wireshake introduction learning notes
Select sort
【Pygame小游戏】这款经典的炸弹人超能游戏上线,你爱了嘛?(附源码)
【Pygame合集】滴~穿越童年游戏指南 请查收:这里面有你玩过的游戏嘛?(附五款源码自取)
Chapter 2 application layer 2.4 DNS
Njupt Nanyou Discrete Mathematics_ Experiment 3
Hyperleger fabric installation
MP框架基本操作(自用)
[pyGame] stir up your brain and play the "24 o'clock" idea together ~ (awesome)