Basic Additions and Deletions Check (CRUD) 01: Paging & Optimistic Lock & Default Insert

Keywords: Java MySQL Mybatis Spring Boot

Basic Additions and Deletions Check (CRUD) 01: Paging & Optimistic Lock & Default Insert

Basic Additions and Deletions Check (CRUD)01
Base Additions and Deletions Check (CRUD)02
Basic Additions and Deletions Check (CRUD)03

Preface

Tip 1: Indirect hesitation, persistent mixing and waiting to die!!! Not desirable or not
Tip 2: The following is the body of this article (this article is only for those little buddies who are not very skilled in configuring and simply using the mybatis plus feature, please bypass it automatically! Hip-Hop)!

1. Project Architecture Building

This case
Development Tool: idea
Technical Architecture: springboot+mybatis+mybatisplus
Database: mysql
Front end: layui

1.1 New Project



1.2 Import Dependencies

The figure above chooses a bunch of dependent build projects and then writes them to pom.xml! Or when you create a project, you can simply copy each applied dependency to him without choosing to create it. Or you can

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.maochang</groupId>
    <artifactId>demo1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo1</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--thymeleaf Template Scene Launcher-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- Scene Launcher-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis  Scene Launcher He and mybatis plus Just one (but I recommend importing them all here)-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
        <!--layui Static Resource Scene Launcher-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>layui</artifactId>
            <version>2.5.5</version>
        </dependency>
        <!--springboot development tool-Hot Deployment Scene Launcher-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
         <!--Database Connection Dependency Scenario Launcher-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--mybatis-plus Test Scene Launcher-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--mybatis-plus Scene Launcher-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>axios</artifactId>
            <version>0.21.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

1.3 Initializing the database

    Put in that bag.sql Run the code inside the suffix file

1.4 Write the application.yml configuration file

1.4.1 yml profile details

spring:
  datasource:
    #Name of the database This is written without changing to just use my line inside the gitee and everything (self-contained)
    url: jdbc:mysql://localhost:3306/t1917school?serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    #Configure static resource resolution
  web:
    resources:
      static-locations: webjars/
    #jackson time formatting Note that this only works for the date type, not for the LocalDateTime    
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
    #mybatisplus detailed configuration
mybatis-plus:
  #Scan Profiles
  mapper-locations: classpath*:/mapper/*Mapper.xml
  #Alias Configuration
  type-aliases-package: com.maochang.demo1.pojo
   #enumeration
  type-enums-package:  com.maochang.demo1.pojo.enums
  #Global Configuration
  global-config:
    db-config:
      #Database Self-Increasing
      id-type: auto
   #To configure    
  configuration:
    #Database field hump
    map-underscore-to-camel-case: false
    #Automatic Mapping
    auto-mapping-behavior: full
    cache-enabled: true #Configured global switch for cache
    lazyLoadingEnabled: true #true #Delayed Loading Switch
    multipleResultSetsEnabled: true #If enabled, all properties of the object are loaded when a property is delayed.
    #Otherwise, load attributes on demand
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #Print sql statements for debugging
server:
  port: 8081# The application port port is occupied and can be changed

1.5 Project Development Package Structure

2. Integrating mybatis-plus

1. Query Interface (Paging Query + Multi-Conditional Query)

    /**
     *
     * @param current Number of bars
     * @param page  limit paging
     * @param
     * @return
     */
    @GetMapping("/queryStu")
    public ResultSet QueryStuinfo(@RequestParam("page") int current, @RequestParam("limit") int page,String stuName,String stuRemark){
        System.out.println(current+"--"+page+"--"+stuName+"---"+stuRemark);
        QueryWrapper<Stuinfo>   queryWrapper= Wrappers.query();
        if(!ObjectUtils.isEmpty(stuName)){
            queryWrapper.eq("stuName",stuName);
        }
        if(!ObjectUtils.isEmpty(stuRemark)&&!stuRemark.equals("0")){
            queryWrapper.eq("stuRemark",stuRemark);
        }
        Page<Stuinfo> psPIPage=new Page<>(current,page);
        Page<Stuinfo>  stuinfoPage=StudentServiceimpl.page(psPIPage,queryWrapper);
        ResultSet resultSet=ResultSet.success1(stuinfoPage);
        resultSet.setMsg("Successful inquiry of students'basic information");
        return resultSet;
    }

2. Add interfaces

 /**
     * New Data
     * @param stuinfo
     * @return
     */
    @PostMapping("/addMessage")
    public ResultSet addMessage( Stuinfo stuinfo){
        stuinfo.setVersion(1);//Optimistic Lock--Field has not found a silent insert method yet
        boolean falg=  StudentServiceimpl.save(stuinfo);
        ResultSet r=new ResultSet();
        if(falg){
            r.setMsg("Insert Successful");
        }else {
            r.setMsg("Insert failed");
        }
        return  r;
    }

3. Delete interface

    /**
     * Single delete (according to id number) ok
     * @param id
     * @return
     */
    @PostMapping("/delMessage")
    public ResultSet delMessage(@RequestParam("id") String id){
       boolean falg=  StudentServiceimpl.removeById(id);
        ResultSet r=new ResultSet();
        if(falg){
            r.setMsg("Delete succeeded");
        }else {
            r.setMsg("Delete failed");
        }
        return  r;
    }

4. Bulk Delete

   /**
     * Bulk Delete ok
     * @param canShuZu
     * @return
     */
    @PostMapping("/delBatches")
    public ResultSet delBatches(@RequestBody String canShuZu[]){
        System.out.println(canShuZu.length+"length");
        QueryWrapper<Stuinfo>   queryWrapper= Wrappers.query();
        queryWrapper.eq("stuNo",canShuZu);
        //This method can be called to delete a table with a primary key id and a column name id
        boolean falg=  StudentServiceimpl.removeByIds(Arrays.asList(canShuZu));
        ResultSet r=new ResultSet();
        if(falg){
            r.setMsg("Bulk Delete Successful");
        }else {
            r.setMsg("Bulk Delete Failure");
        }
        return  r;
    }

5. Modify the interface

  /**
     * Change user information
     * @param stuinfo
     * @return
     */
    @PostMapping("/updateMessage")
    public ResultSet updaeMessage(@RequestBody  Stuinfo stuinfo){
        System.out.println(stuinfo.toString()+"Maochang");
        //UpdateWrapper<Stuinfo> aa=Wrappers.update();
        System.out.println(stuinfo.getId());
        boolean falg=  StudentServiceimpl.updateById(stuinfo);
        ResultSet r=new ResultSet();
        if(falg){
            r.setMsg("Successful modification");
        }else {
            r.setMsg("Modification failed");
        }
        return  r;
    }

5. Optimistic Lock

5.1. Add a field to the table

Add to Table  version  Field initialization value is 1

5.2 Set field annotations

Entity Class  version  Add a comment to the field @Version

5.3 Configure optimistic lock interceptor mybatisPlus Interceptor

Configure Optimistic Lock Component 
//Optimistic Lock Interceptors and Paging Interceptors are configured in this class 
@Configuration //Declare this class as a configuration class This is also a component that will be scanned
@MapperScan("com.maochang.demo1.mapper")
@Slf4j
public class MybatisPlusConfig  {
    /**
     * New Paging Plugin,
     * One mitigation followed the rules of mybatis,
     * MybatisConfiguration#useDeprecatedExecutor = false needs to be set
     * Avoid caching problems
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        //mybatis plus interceptor
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //Paging Class
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //Pessimistic Lock
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
    /**
     * No results after half a day's search
     * setUseDeprecatedExecutor According to the official website,
     * The next version will be deleted, and now you have to configure it to avoid caching problems. The line is still there. It's extremely uncomfortable for obsessive-compulsive disorder.
     * He is trying to avoid caching problems (this property will be removed when the old plugin is removed)
     * @return
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

6. Automatic Filling

6.1 Add two fields to the table

Typical insertion time of data,Update times are automatically inserted,Although you can set it up through a database
 Default value,But we don't usually do that.       

6.2 Setting field annotations

@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")//Time Date Formatting 
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")//Time Date Formatting
@TableField(fill = FieldFill.INSERT)
private LocalDateTime  insertTime;
	
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;

6.3 Configuring MetaObjectHandler

Configure AutoFill Component 
/**
 * @author lucky monkey
 * @version 1.0
 * @date 2021-10-13 20:23
 */
@Slf4j
@Component //Always add to ioc container or it will not take effect
public class MyMetaObjectHandler  implements MetaObjectHandler {

    //Insert Property Auto-Fill
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        //This.strictInsertFill (metaObject,'insertTime', LocalDateTime.class, LocalDateTime.now()); //Starting Version 3.3.0 (Recommended)
        // perhaps
        //MetaObject metaObject, String = null fieldName, Class<T> fieldType, E fieldVal
        this.strictInsertFill(metaObject, "insertTime", () -> LocalDateTime.now(), LocalDateTime.class); // Starting Version 3.3.3 (Recommended)
        this.strictInsertFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // Starting Version 3.3.3 (Recommended)
        //This.strictInsertFill (metaObject,'version', Integer.class, 1); //Starting Version 3.3.3 (Recommended)
        // perhaps
        //This.fillStrategy (metaObject,'createTime', LocalDateTime.now()); //You can also use (3.3.0 method has bugs)
    }
    //Update attribute autofill
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // Starting Version 3.3.0 (Recommended)
        // perhaps
        //This.strictUpdateFill (metaObject,'updateTime', () -> LocalDateTime.now (), LocalDateTime.class); //Starting Version 3.3.3 (Recommended)
        // perhaps
        //This.fillStrategy (metaObject,'updateTime', LocalDateTime.now()); //You can also use (3.3.0 method has bugs)
    }
}

7. Logical Delete

Delete points
 Logical Delete:Delete directly from the database
 Physical Delete:Not removed from database,Instead, it invalidates him by a variable! deleted=0=>deleted=1
 Application Scenarios: Administrators can view deleted records! Prevent data loss,Similar to Recycle Bin! 
Drop in Recycle Bin,Logical deletion is a way to facilitate data recovery and protect the value of the data itself, etc.
Schema, but it is actually deletion. If you need to find it out frequently, you should not use logical deletion, but use a state to represent it.
Essentially a update operation
 say    bright: Automatic injection only sql Effective 
          insert: No restrictions
          lookup: Append where Conditional filter for deleted data,And use wrapper.entity 
          Generated where The condition ignores the field
          To update: Append where Conditions to prevent updates to deleted data,And use 
          wrapper.entity    Generated where The condition ignores the field
          delete: Change to Update
 example    as:
          delete: update user set deleted=1 where id = 1 and deleted=0
          lookup: select id,name,deleted from user where deleted=0 
Field Type Support Description:
          Supports all data types(Recommended Use Integer,Boolean,LocalDateTime)
          If a database field is used datetime,Logically Deleted and Deleted Values Support Configuration
          Is String null,Another value supports configuring functions to obtain values such as now()                      

7.1 Add a field to the table

 Add one to the table deleted Field default value equal to 0 (meaning not deleted)

7.2 Set field annotations

 Adding attributes to an entity class must have one deleted Fields correspond to database fields
@TableLogic
private Integer deleted;

7.3 Configure GlobalConfig$DbConfig

Configuration Logical Delete Component 
mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag  # Entity field names that are logically deleted globally (since 3.3.0, step 2 can be ignored after configuration)
      logic-delete-value: 1 # Logically deleted value (default 1)
      logic-not-delete-value: 0 # Logically undeleted value (default 0)

8. Conditional Constructor

AbstractWrapper
QueryWrapper(LambdaQueryWrapper) and UpdateWrapper(Lambda UpdateWrapper) The parent class of the sql Of where condition, entity Attributes are also used to generate sql Of      where Conditional note: entity Generated where Conditions and use of individual api Generated  where Conditions have no associated behavior

8.1 Conditional Constructor Basic Methods


Use the methods in the detailed documentation on plus. Current project only uses queryWrapper

8.2QueryWrapper

change select condition--Later Supplement

8.3UpdateWrapper

change set  condition--Later Supplement

8.4 Customize SQL using Wrapper

Matters needing attention:
Need mybatis-plus Edition >= 3.0.7 param Parameter name or name ew,Or add notes  
@Param(Constants.WRAPPER) Use ${ew.customSqlSegment} I won't support it 
Wrapper Internal entity generate where Sentence

8.4.1 with Notes

@Select("select * from mysql_data ${ew.customSqlSegment}")
List<MysqlData> getAll(@Param(Constants.WRAPPER) Wrapper wrapper);

8.4.2 using xml

List<MysqlData> getAll(Wrapper ew);
<select id="getAll" resultType="MysqlData">
	SELECT * FROM mysql_data ${ew.customSqlSegment}
</select>

2. Integrating layui to generate html pages

First import layui's css package and layui's js package


Note: If you have integrated thymeleaf braces on the page, you must write as an example in the code below me, or you will get an error.

1. Initialization of table tables

Basic use of 1.1 layui

 layui.use(['layer','form','table','laydate'], function(){
        let layer = layui.layer
            ,form = layui.form
            ,table=layui.table
            ,$=layui.$
            ,laydate=layui.laydate
     //Only if you write something like this can you use it           
 });

1.2 Table Initialization

  table.render({
             elem: '#demo'
            ,url: '/queryStu' //data interface
            ,toolbar: '#default1'// Opens the toolbar, where the default icon is displayed to customize the template, as detailed in the documentation
            // , totalRow: true //Open the total line
            ,id:"demo"
            ,cols: [
                [ //Table Head
                 {type: 'checkbox',fixed: 'left'},
                 {field: 'id', width:'80',title: 'number',sort: true,fixed: 'left',hide:true}
                 ,{field: 'stuNo',width:'100',title: 'School Number',sort: true,fixed: 'left'}
                ,{field: 'stuName',width:'100',title: 'Full name'}
                ,{field: 'stuSex', width:'100',title: 'Gender'}
                ,{field: 'stuAge', width:'100',title: 'Age',hide:true}
                ,{field: 'stuClass', width:'100',title: 'class'}
                ,{field: 'stuHobby', width:'100',title: 'hobby',hide:true}
                ,{field: 'stuPhoto', width:'100',title:'Photo'}
                ,{field: 'stuBirthday', width:'100',title:'Birthday'}
                ,{field: 'stuRemark',width:'100',title:'role',templet: "#juese"}
                ,{field: 'insertTime', width:'100',title:'Insert Time',hide:true}
                ,{field: 'updateTime', width:'100',title:'Update Time',hide:true}
                ,{field: 'version',width:'100',title:'version number',hide:true}
                ,{field:'sex', title:'Gender', width:85, templet: '#switchTpl', unresize: true}
                ,{field:'lock', title:'Is Locked', width:110, templet: '#checkboxTpl', unresize: true}
                ,{field: 'stuRemark',width:'185',title:'operation',toolbar:'#barDemo'}
            ]
            ],
            page:{
                limit:3,
                limits:[3,6,9]},
});

2. Row toolbar-Header toolbar

2.1 Line Toolbar Template

<script type="text/html"  id="default1">
  <div class="layui-btn-container">
      <button class="layui-btn layui-btn-sm" lay-event="getCheckData">Delete selected rows</button>
      <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">Get Selected Number</button>
      <button class="layui-btn layui-btn-sm" lay-event="isAll">Verify that all are selected</button>
      <button class="layui-btn layui-btn-sm" lay-event="addMessage">Add data</button>
      <button class="layui-btn layui-btn-sm" lay-event="getCheckData">Get selected row data</button>
  </div>
</script>

2.2 Line Toolbar Listening

//Listen for Line Tool Events
        table.on('tool(test)', function(obj){
            let data = obj.data;
            let form=layui.form;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('Really delete line?', function(index){
                    obj.del();
                    console.log(data.id);
                    delMessage(data.id)
                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                let sj=data;//Get edit row data
                chaJueSe() //Initialize Role Dropdown
            }
        });

3. Selectect drop-down box dynamic data display

 //Query Role Message
        function chaJueSe() {
            let  $ =layui.$;
            let  layer=layui.layer;
            //This one has to be tested
            $.post("/chaJueSe",function(data){
                console.log(data);//information
                $(".badwid").append(new Option("--Please select--","0"));
                $.each(data.data,function (index,item) {   //json data returned in loop background
                    //The new Option method creates a new option. The first parameter is the value to be displayed, the second parameter is the value of the option, and append to the drop-down box.
                    $('#badwid').append(new Option(item.jsname,item.id));
                })
                layui.form.render("select");
            });
        }

4. Date control initialization

4.1 Date Control Effects

4.2 Date Control Code

      <div class="layui-form-item">
          <div class="layui-inline">
              <label class="layui-form-label">Birthday:</label>
              <div class="layui-input-inline">
                  <input type="text" name="stuBirthday" id="stuBirthday" lay-verify="stuBirthday" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
              </div>
          </div>
      </div>
   //Date Instance Initialization
     laydate.render({
            elem: '#stuBirthday'
     });

5. Template Grammar Nesting

5.1 Gender Slide Button Template

<script type="text/html" id="switchTpl">
    <!-- There checked The status of is just a demonstration  d.Sex column-->
    <input type="checkbox" name="sex" value="{{d.stuSex}}" lay-skin="switch" lay-text="female|male" lay-filter="sexDemo"{{d.stuSex=="female"?"checked":""}} >
</script>

5.2 Gender Slide Button Monitor

 //Monitor gender operations
        form.on('switch(sexDemo)', function(obj){
            layer.tips(this.value + ' ' + this.name + ': '+ obj.elem.checked, obj.othis);
        });

5.3 Whether to lock the button template

<script type="text/html" id="checkboxTpl">
    <!--There checked The status of is just a demonstration -->
    <!--{{ d.id == 10006 ? 'checked' : '' }} This can be written directly into the label to make an initial display judgment-->
    <input type="checkbox" name="lock" value="{{d.id}}" title="locking" lay-filter="lockDemo" checked>
</script>

5.4 Whether to lock the button to listen

   //Listen for lock operations
        form.on('checkbox(lockDemo)', function(obj){
            layer.tips(this.value + ' ' + this.name + ': '+ obj.elem.checked, obj.othis);
        });

5.5 Cell Role Data Template Judgment

<!--Role Judgment Template-->
<script type="text/html" id="juese">
    {{#  if(d.stuRemark == "1"){  }}
     <span>Monitor</span>
    {{# }else if(d.stuRemark == "2"){ }}
    <span>Deputy monitor</span>
    {{# }else if(d.stuRemark == "3"){ }}
    <span>Youth League Committee</span>
    {{# }else if(d.stuRemark == "4"){ }}
    <span>Group leader</span>
    {{# }else if(d.stuRemark == "5"){ }}
    <span>Deputy Group Leader</span>
    {{# }else if(d.stuRemark == "6"){ }}
    <span>Group members</span>
    {{# } }}
</script>

Their correspondence is that each script's id selector corresponds to the initial table table

6. Ejection Layer

6.1 Pop-up Layer Template

<div id="addDiv" style="display: none" class="layui-form-item" >
    <form class="layui-form" action="" style="margin-top: 40px; margin-left: 100px" id="formbd" lay-filter="addform">
        <div class="layui-form-item" style="display: none">
            <div class="layui-inline">
                <label class="layui-form-label">Primary key id: </label>
                <div class="layui-input-inline">
                    <input type="tel" name="id" lay-verify="required|phone" autocomplete="off" class="layui-input">
                </div>
            </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">School Number:</label>
            <div class="layui-input-inline">
                <input type="tel" name="stuNo" lay-verify="required|phone" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">Full name:</label>
            <div class="layui-input-inline">
                <input type="text" name="stuName" lay-verify="email" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">Gender:</label>
        <div class="layui-input-block">
            <input type="radio" name="stuSex" value="male" title="male" checked="">
            <input type="radio" name="stuSex" value="female" title="female" >
            <!--<input type="radio" name="sex" value="Prohibited" title="Disable" disabled="">-->
        </div>
    </div>
    <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">Age:</label>
                <div class="layui-input-inline">
                    <input type="text" name="stuAge" lay-verify="email" autocomplete="off" class="layui-input">
                </div>
            </div>
     </div>
     <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">Class:</label>
                <div class="layui-input-inline">
                    <input type="text" name="stuClass" lay-verify="email" autocomplete="off" class="layui-input">
                </div>
            </div>
      </div>
      <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">Hobbies:</label>
                <div class="layui-input-inline">
                    <input type="text" name="stuHobby" lay-verify="email" autocomplete="off" class="layui-input">
                </div>
            </div>
      </div>
      <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">Photo:</label>
                <div class="layui-input-inline">
                    <input type="text" name="stuPhoto" lay-verify="email" autocomplete="off" class="layui-input">
                </div>
            </div>
      </div>
      <div class="layui-form-item">
          <div class="layui-inline">
              <label class="layui-form-label">Birthday:</label>
              <div class="layui-input-inline">
                  <input type="text" name="stuBirthday" id="stuBirthday" lay-verify="stuBirthday" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
              </div>
          </div>
      </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">Roles:</label>
                <div class="layui-input-block" style="width: 190px">
                    <select name="stuRemark" lay-filter="aihao" id="badwid"  >
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">Edition:</label>
                <div class="layui-input-inline">
                    <input type="text" name="version" id="version" lay-verify="version" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
    </form>
</div>

6.2 Pop-up Layer Code

 layer.open({
                        type: 1,
                        area: ['600px', '730px'], //Width and height
                        content: $('#addDiv', //here content is a DOM, note: it is best to store the element outermost of the body, otherwise it may be affected by other relative elements
                        btn:["Determine","cancel"],
                        title:"Add Information",
                        yes(){
                            // Layer.alert (OK)
                            addMessage(); //Form Submission Information Add Method
                            console.log("Determine")
                            $("#formbd")[0].reset();
                             let d= layer.index;
                            layer.close(d); //If yes callback is set, manual shutdown is required
                        },
                        btn2: function(index, layero){  //Callback of Button [Button 2]
                            //return false Opens the code to prevent clicking the button to close
                            $("#formbd")[0].reset();
                            console.log("cancel")
                            let d= layer.index;
                            layer.close(d); //If yes callback is set, manual shutdown is required
                        },
                        cancel: function(){         //Upper right corner closes callback
                            //return false Opens the code to prevent clicking the button to close
                            console.log("Wrong number");
                            $("#formbd")[0].reset();
                            let d= layer.index;
                            layer.close(d); //If yes callback is set, manual shutdown is required
                        }
                    });

7. Edit Button Row Data Echo to from Form

   table.on('tool(test)', function(obj){
            let data = obj.data;//Get edit row data
            let form=layui.form;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('Really delete line?', function(index){
                    obj.del();
                    console.log(data.id);
                    delMessage(data.id)
                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                let sj=data;
                chaJueSe() //Initialize Role Dropdown
                layer.open({
                    type: 1,
                    area: ['600px', '730px'], //Width and height
                    content: $('#addDiv', //here content is a DOM, note: it is best to store the element outermost of the body, otherwise it may be affected by other relative elements
                    btn:["Determine","cancel"],
                    title:"Modify Information",
                    yes(){
                        console.log("Confirm Modification")
                        updateMessage();//Modify the ajax method
                    },
                    btn2: function(index, layero) {  //Callback of Button [Button 2]
                        console.log("Cancel Modification")
                    },
                    cancel: function(){         //Upper right corner closes callback
                       console.log("close button")
                    },
                    success: function(layero, index){
                        //Assign a value to the form
                     form.val("addform", { //formTest is the value corresponding to the element attribute lay-filter="" where class="layui-form"
                             "id": data.id
                            ,"stuNo": data.stuNo
                            ,"stuName": data.stuName// "name": "value"
                            ,"stuSex": data.stuSex
                            ,"stuAge": data.stuAge
                            ,"stuClass": data.stuClass
                            ,"stuHobby": data.stuHobby
                            ,"stuPhoto": data.stuPhoto
                            ,"stuBirthday": data.stuBirthday
                            ,"stuRemark": data.stuRemark
                            ,"version": data.version
                     });

                     //Form Refresh Echo
                     form.render();
                    }
                });
            }
        });

8. Multi-condition Query Condition List Submission

  //Multi-Conditional Query Button Submit
        form.on('submit(tjao)', function(data){
            table.reload('demo', {
                 elem: '#demo'
                ,url: '/queryStu', //Setting up asynchronous interfaces
                 where:data.field
                ,page: {
                    curr: 1, //Start again on page 1
                    limit:3,
                    limits:[3,6,9]
                }
            }); //Overload data only
            return false;
        });
        //Multi-Conditional Query-Dropdown Box Listens for Events
        form.on('select(badwid2)', function(data){
            alert(data.value);
            table.reload('demo', {
                elem: '#demo'
                ,url: '/queryStu', //Setting up asynchronous interfaces
                where:{'stuRemark': data.value}
                ,page: {
                    curr: 1, //Start again on page 1
                    limit:3,
                    limits:[3,6,9]
                }
            }); //Overload data only
            return false;
        });

9.The difference between the post() method of Ajax and the ajax() method in modifying data is that one uses @RequestBody and the other does not


End!

summary

Tip: Here is a summary of the article:
For example: That's what we're going to talk about today. This article just briefly introduces the use of pandas, which provides a number of functions and methods that enable us to process data quickly and easily.

Posted by saadatshah on Sat, 16 Oct 2021 10:10:57 -0700