当前位置:网站首页>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

In front of Conditions  

rely on   

  Configuration information yml 

mapping problem

  The rules Table name  

​ edit

  The rules   Primary key  

Set the field mapping relationship

Based on using  

  Basic query No, Conditions

  add to  

  Delete  

modify

Condition selector

QueryWrapper

      Common conditions

        Basic use

UpdateWrapper

    Basic use

Custom method (mapper Interface )

Paging query

    Get ready   Pagination plug-in unit

  Single table query       

  Multi-table query  

Service

Before transformation

  After transformation

Custom method

Auto fill

  Logical deletion


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

原网站

版权声明
本文为[m0_ sixty-one million four hundred and ninety-nine thousand thr]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206102250310116.html