71 - advertising management module and user management module of the project

Advertising management module and user management module of the project

In the last blog (Chapter 70 blog), we completed the course management module, and then we completed the advertising management module and user management module
Advertising management module:
Realize the following functions:
Advertising space list query
Add ad space
Echo advertising space name
Modify advertising space
Advertisement paging query
Picture upload
New advertisement
Echo advertising information
Modify advertisement
Advertising status online and offline

The corresponding database table is found in the blog in Chapter 70
Table relationship introduction:
ER diagram:

The corresponding field information can be seen in the table
Implementation of advertising management module:
Advertisement list query:
requirement analysis
Demand: click the advertisement list button to display the advertisement list
Dao layer: PromotionSpaceMapper:
package com.lagou.dao;

import com.lagou.domain.PromotionSpace;

import java.util.List;

/**
 *
 */
public interface PromotionSpaceMapper {

    /*
    Get all advertising spaces
     */
    public List<PromotionSpace> findAllPromotionSpace();
}

Corresponding mapping configuration file (promotionspacemapper. XML):
<?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.lagou.dao.PromotionSpaceMapper">

    <!--Query all advertising spaces-->
    <select id="findAllPromotionSpace" resultType="PromotionSpace">
        select *
        from promotion_space
    </select>
</mapper>
Service layer: PromotionSpaceService and its implementation classes:
package com.lagou.service;

import com.lagou.domain.PromotionSpace;

import java.util.List;

/**
 *
 */
public interface PromotionSpaceService {

    /*
    Get all advertising spaces
     */
    public List<PromotionSpace> findAllPromotionSpace();
}

package com.lagou.service.impl;

import com.lagou.dao.PromotionSpaceMapper;
import com.lagou.domain.PromotionSpace;
import com.lagou.service.PromotionSpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class PromotionSpaceServiceImpl implements PromotionSpaceService {

    @Autowired
    private PromotionSpaceMapper promotionSpaceMapper;

    /*
   Get all advertising spaces
    */
    @Override
    public List<PromotionSpace> findAllPromotionSpace() {
        List<PromotionSpace> allPromotionSpace = promotionSpaceMapper.findAllPromotionSpace();

        return allPromotionSpace;
    }
}

Web tier: PromotionSpaceController:
package com.lagou.controller;

import com.lagou.domain.PromotionSpace;
import com.lagou.domain.ResponseResult;
import com.lagou.service.PromotionSpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("/PromotionSpace")
public class PromotionSpaceController {

    @Autowired
    private PromotionSpaceService promotionSpaceService;

    /*
  Get all advertising spaces
   */
    @RequestMapping("/findAllPromotionSpace")
    public ResponseResult findAllPromotionSpace(){
        List<PromotionSpace> allPromotionSpace = promotionSpaceService.findAllPromotionSpace();

        ResponseResult responseResult = new ResponseResult(true, 200, "Query all advertising spaces successfully", 
                                                           allPromotionSpace);
        return responseResult;
    }

}

Test interface using Postman
Add ad space
requirement analysis
Add: click the advertisement list button to display the advertisement list

Dao layer: add some PromotionSpaceMapper:
/*
    Add ad space
     */
    public void savePromotionSpace(PromotionSpace promotionSpace);
Add some promotionspacemapper xml:
  <!--Add ad space-->
    <insert id="savePromotionSpace" parameterType="PromotionSpace">
        insert into promotion_space values(null, #{name}, #{spaceKey}, 
        #{createTime}, #{updateTime}, #{isDel})

<!--
Here's an explanation: corresponding replacement is to use get Method, if not get Method is assigned directly
 And others get The case of the first letter of the following name is ignored, and the direct assignment must be consistent

Here, without so and so get Method or set Methods can also be said to have no matching correspondence get Method and correspondence set method

When all operations are not found, an error will be reported. For example, there is no correspondence here get Method and the corresponding directly assigned variable will report an error
-->
    </insert>
Service layer: add some PromotionSpaceService and its implementation classes:
    /*
    Add ad space
     */
    public void savePromotionSpace(PromotionSpace promotionSpace);
/*
    Add ad space
     */
    @Override
    public void savePromotionSpace(PromotionSpace promotionSpace) {
        promotionSpace.setSpaceKey(UUID.randomUUID().toString());
        //UUID is a class that comes with java
        Date date = new Date();
        promotionSpace.setCreateTime(date);
        promotionSpace.setUpdateTime(date);
        promotionSpace.setIsDel(0);

        promotionSpaceMapper.savePromotionSpace(promotionSpace);
    }
Web tier: add some PromotionSpaceController:
/*
    Add ad space
    Extensions that will be modified later
     */
    @RequestMapping("/saveOrUpdatePromotionSpace")
    public ResponseResult saveOrUpdatePromotionSpace(@RequestBody PromotionSpace promotionSpace){
        promotionSpaceService.savePromotionSpace(promotionSpace);
        ResponseResult responseResult = new ResponseResult(true, 200, "Ad space added successfully",null);
        return responseResult;
    }
Test interface using Postman
We need to echo before making changes
Echo advertising space name
requirement analysis
Demand: click the Edit button to display the advertising space information

Dao layer: add some PromotionSpaceMapper:
/*
    Query advertising space information according to id
     */
    public PromotionSpace findPromotionSpaceById(Integer id);
Add some promotionspacemapper xml:
 <!--according to id Query advertising space information-->
    <select id="findPromotionSpaceById" parameterType="int" resultType="PromotionSpace">
        select id,name
        from promotion_space where id = #{id}
    </select>
Service layer: add some PromotionSpaceService and its implementation classes:
  /*
  Query advertising space information according to id
   */
    public PromotionSpace findPromotionSpaceById(Integer id);
   /*
Query advertising space information according to id
*/
    @Override
    public PromotionSpace findPromotionSpaceById(Integer id) {
        PromotionSpace promotionSpaceById = promotionSpaceMapper.findPromotionSpaceById(id);

        return promotionSpaceById;
    }
Web tier: add some PromotionSpaceController:
 /*
    Query advertising space information according to id
     */
    @RequestMapping("/findPromotionSpaceById")
    public ResponseResult findPromotionSpaceById(Integer id) {
        //In fact, we get the corresponding int (judge Integer, then String becomes int, and then automatic packing)
        PromotionSpace promotionSpace = promotionSpaceService.findPromotionSpaceById(id);

        ResponseResult responseResult = new ResponseResult(true, 200, "Successful query of specific advertising space", 
                                                           promotionSpace);
        return responseResult;

    }
Test interface using Postman
After echo, we modify:
Modify: on the basis of page echo, click the submit button to really modify the data

Dao layer: add some PromotionSpaceMapper:
 /*
   Modify advertising space
    */
    public void updatePromotionSpace(PromotionSpace promotionSpace);
Add some promotionspacemapper xml:
 <!--Modify advertising space-->
    <update id="updatePromotionSpace" parameterType="PromotionSpace">
            update promotion_space set name = #{name},updateTime = #{updateTime} where id = #{id}
    </update>
Service layer: add some PromotionSpaceService and its implementation classes:
/*
  Modify advertising space
   */
    public void updatePromotionSpace(PromotionSpace promotionSpace);
   /*
    Modify advertising space
     */
    @Override
    public void updatePromotionSpace(PromotionSpace promotionSpace) {

        promotionSpace.setUpdateTime(new Date());
        promotionSpaceMapper.updatePromotionSpace(promotionSpace);
    }
Web layer: modify some PromotionSpaceController (extend saveOrUpdatePromotionSpace method):
 @RequestMapping("/saveOrUpdatePromotionSpace")
    public ResponseResult saveOrUpdatePromotionSpace(@RequestBody PromotionSpace promotionSpace){

        ResponseResult responseResult;
        if(promotionSpace.getId() == null) {
            promotionSpaceService.savePromotionSpace(promotionSpace);
            responseResult = new ResponseResult(true, 200, "Ad space added successfully", null);
        }else{
            promotionSpaceService.updatePromotionSpace(promotionSpace);
            responseResult = new ResponseResult(true, 200, "Advertisement space modified successfully", null);
        }
        return responseResult;
    }
Test interface using Postman
Advertisement paging query
requirement analysis
Demand: click the advertisement list to display the advertisement information in a paginated list

Before that, we need to transform the corresponding class (PromotionAd):
Add the corresponding variable and its get and set methods
//Declare one party relationship: PromotionSpace
    private PromotionSpace promotionSpace;

    public PromotionSpace getPromotionSpace() {
        return promotionSpace;
    }

    public void setPromotionSpace(PromotionSpace promotionSpace) {
        this.promotionSpace = promotionSpace;
    }
Make the corresponding relationship appear (although the table has no corresponding foreign key, it will not affect the operation, but redundant data may appear in your own operation or under special circumstances)
Generally, if there is no error in the front-end data transmission, it will generally correspond directly without redundant data. However, if there is no foreign key connection, the corresponding query may be slow
If the table has a foreign key connection, the development efficiency is a little lower, because it is difficult to try and error (such as adding manually). The most important thing is that it is difficult to change when changing (especially when changing the business)
In this case, the maintenance and efficiency of the table will appear. Generally, we will not query through the foreign key, but through the primary key (this is generally set because it only contacts itself)
In other words, this efficiency can not be very demanding
If we want to use foreign keys in the future, it is best not to modify them because of the possibility of maintenance
When you are sure that it will not be modified, you can try to make foreign key contact, of course, you can not use it (to prevent sudden modification, because there will be business)
To sum up: generally, we will not use foreign keys in the face of maintainability
Redundant data elimination is a little redundant (because it can be realized by program, as long as the program will not make mistakes)
Dao layer: PromotionAdMapper:
package com.lagou.dao;

import com.lagou.domain.PromotionAd;

import java.util.List;

/**
 *
 */
public interface PromotionAdMapper {

    /*
    Paging query of advertising information
     */
    public List<PromotionAd> findAllPromotionAdByPage();
}

Corresponding mapping configuration file (PromotionAdMapper.xml):
<?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.lagou.dao.PromotionAdMapper">

    
    <resultMap id="ad_space" type="PromotionAd">

        <id property="id" column="id"></id>
        <result property="name" column="name"></result>
        <result property="spaceId" column="spaceId"></result>
        <result property="keyword" column="keyword"></result>
        <result property="htmlContent" column="htmlContent"></result>
        <result property="text" column="text"></result>
        <result property="link" column="link"></result>
        <result property="startTime" column="startTime"></result>
        <result property="endTime" column="endTime"></result>
        <result property="createTime" column="createTime"></result>
        <result property="updateTime" column="updateTime"></result>
        <result property="status" column="status"></result>
        <result property="priority" column="priority"></result>
        <result property="img" column="img"></result>

        <association property="promotionSpace" javaType="PromotionSpace" 
                     select="com.lagou.dao.PromotionSpaceMapper.findPromotionSpaceById" 
                     column="spaceId">
             </association>
    <!--If the data we query is specified, the label is required to specify when operating the objects in the class, and the default specification is used here-->
    </resultMap>

    <!--Paging query of advertising information-->
    <!--Note: there may be variables with relationships set in the class, but the table may not necessarily be set, such as foreign keys and primary keys (primary keys are usually set)-->
    
    <select id="findAllPromotionAdByPage" resultMap="ad_space">
            select * from promotion_ad
    </select>
    <!--
    Note: the configuration file is best placed in the resource folder. Although the final result is placed under the project, it will only be identified in the resource folder during identification
    That is, although src And resources The final storage of the path is the same, but the corresponding configuration file is placed in the src inside
    maven Not going src Identify, but go resources Identify that all configuration files are preferably in resources Inside the folder
    This is using maven Don't pay attention to anything else maven Yes, usually not
    Because they are written directly to the final path without identifying the operation
    -->
</mapper>
To use the paging operation of Mybatis, we usually need to configure the plug-in, but the configuration file in Mybatis has been integrated by Spring
All we need to configure in the corresponding integration places, as follows:
Applicationdao.context add section XML (extended ApplicationContext Dao. XML):
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.lagou.domain"></property>
        <property name="plugins">  <!--Configure plug-ins-->
            <array>
                <bean class="com.github.pagehelper.PageHelper">
                    <property name="properties">
                        <value>helperDialect=mysql</value>
                    </property>
                </bean>
            </array>
            <!--
These operations are equivalent to Mybatis Inside
 <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql"/>
           dialect Specify the dialect, because the corresponding paging operations of different databases are different, such as mysql yes limit
        </plugin>
    </plugins>
Because there are many plug-ins, it is array Label (set)
-->
        </property>
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
    </bean>
Now we can write the Service layer, but the front end usually passes two parameters. We can use two parameters to receive it or a class to receive it
Here, we use classes to receive and prevent the transfer of multiple parameters in the future (using classes, we basically only need to modify the Service layer)
Write the PromotionAdVo class
This class is not used to store the information of two table fields, but to store specific parameters
In fact, they all have the same function
According to the parameters, the former stores the information of two tables, and the latter stores the corresponding required parameters, but they are all variables
It also realizes the operation with good maintainability, and there are no redundant variables, that is, the same operation with less code
According to the table, the former is to realize the parameter consolidation of the table, while the latter is only to store the required parameters
When we use entity class parameters, we usually use entity class parameters directly, because there is a corresponding class (entity class exists)
Of course, if it's not too troublesome, you can also create corresponding classes to store corresponding parameters
However, no matter which one is used, it is to solve the needs and facilitate maintenance. When there is a better one, it must be used better:
package com.lagou.domain;

/**
 *
 */
public class PromotionAdVo {

    //Current page
    private Integer CurrentPage;

    //Number of items displayed per page
    private Integer PageSize;

    public Integer getCurrentPage() {
        return CurrentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        CurrentPage = currentPage;
    }

    public Integer getPageSize() {
        return PageSize;
    }

    public void setPageSize(Integer pageSize) {
        PageSize = pageSize;
    }
}

Next, we write the Service layer
Service layer: PromotionAdService and its implementation classes:
package com.lagou.service;

import com.github.pagehelper.PageInfo;
import com.lagou.domain.PromotionAd;
import com.lagou.domain.PromotionAdVo;

import java.util.List;

/**
 *
 */
public interface PromotionAdService {

    /*
 Paging query of advertising information
  */
    public PageInfo<PromotionAd> findAllPromotionAdByPage(PromotionAdVo promotionAdVo);
}

package com.lagou.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lagou.dao.PromotionAdMapper;
import com.lagou.domain.PromotionAd;
import com.lagou.domain.PromotionAdVo;
import com.lagou.service.PromotionAdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class PromotionAdServiceImpl implements PromotionAdService {

    @Autowired
    private PromotionAdMapper promotionAdMapper;

    /*
 Paging query of advertising information
  */
    @Override
    //Note: java will recognize the < > coincidence bit separator, that is to say
    //Pageinfo < promotionad > findallpromotionadbypage and pageinfo < promotionad > findallpromotionadbypage
    //It's the same. Although the latter ones are close together, they are actually separated. When interpreted as class, they will be separated
    //The classes corresponding to the target in maven store class files instead of java files. You can click and have a look
    public PageInfo<PromotionAd> findAllPromotionAdByPage(PromotionAdVo promotionAdVo) {
        //If paging is used, the corresponding parameters will be changed during the execution of sql statements
        //The limit statement is used to implement the sql operation
        //You can see in the log:
        //Preparing: select * from promotion_ad limit ?,? 
        //Parameters: 0(Integer), 5(Integer) 
        //Above form
        PageHelper.startPage(promotionAdVo.getCurrentPage(),promotionAdVo.getPageSize());

        List<PromotionAd> allPromotionAdByPage = 
            promotionAdMapper.findAllPromotionAdByPage(promotionAdVo);

        //We have obtained the corresponding data according to the corresponding paging operation above, but we need some other data according to the demand. The corresponding data is as follows
        //To obtain these data, you need to pass the address of the parameter (that is, the address of the list set above)
        //To determine the corresponding data, because when we use paging
        //That is, when splicing sql statements, the address information of the obtained data will be retained
        //When this address is determined, we can obtain the data obtained from the paging of our operation, because we need to obtain the paging data
        //Generally, there will be the total number of entries, the number of entries displayed on the current page, the total number of pages, the current page, the data of the current page, etc
        //Before splicing, we will operate on the parameters of the passed startPage method
        //For these operations, corresponding data will be required, such as the corresponding data above
        //And get the corresponding data (such as list set). When we execute the corresponding sql, we splice the sql and return the executed data
        //Before returning, the data is bound with the obtained address, that is, the data can only be obtained through this address
        //Otherwise, the corresponding data cannot be obtained
        //For example, if you give an address that has not been stored, the corresponding data is generally the default value
        //Such as 0, or false (the default value of boolean type is false, which is the basis. Don't make a mistake), etc
        //Therefore, the following parameters are the obtained data (here is the list set), but generally only manipulate the list set (only the list set in the source code)
        //Because there is no need to page multiple pieces of data, the PageInfo class only operates on the list collection
        PageInfo<PromotionAd> promotionAdPageInfo = new PageInfo<>(allPromotionAdByPage);
 	
        return promotionAdPageInfo; //Return the corresponding data
    }
}

As shown in the figure (log):

It can be found that the log is indeed spliced, and the corresponding parameters are 0 and 5. Because the parameters passed by the front end are 1 and 5, 1 represents the current page and 5 represents the number of queries
It is found that the corresponding parameters 0 and 5 are indeed the first page and 5 items are queried. This is because limit 0 and 5 in sql means that 5 items are queried starting from the first item (subscript 0)
Web tier: PromotionAdController:
package com.lagou.controller;

import com.github.pagehelper.PageInfo;
import com.lagou.domain.PromotionAd;
import com.lagou.domain.PromotionAdVo;
import com.lagou.domain.ResponseResult;
import com.lagou.service.PromotionAdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 */
@RestController
@RequestMapping("/PromotionAd")
public class PromotionAdController {

    @Autowired
    private PromotionAdService promotionAdService;

    /*
    Advertisement paging query
     */
    //In fact, the annotation does not have to be written on the operated object
    //As long as the conforming operation object is the next one of the annotation, so the annotation can be written on the left of the variable
    //Or @ RequestMapping("/findAllPromotionAdByPage") public ResponseResult (omitted) in this way
    @RequestMapping("/findAllPromotionAdByPage")
    public ResponseResult findAllPromotionAdByPage(PromotionAdVo promotionAdVo){
        PageInfo<PromotionAd> allPromotionAdByPage = 
            promotionAdService.findAllPromotionAdByPage(promotionAdVo);
        //allPromotionAdByPage contains other paging data and queried data
        ResponseResult responseResult = new ResponseResult(true, 200, "Advertisement paging query succeeded", 
                                                           allPromotionAdByPage);

        return responseResult;
    }
}

Test interface using Postman
Image upload interface
requirement analysis
Requirements: add an advertisement page and click the upload button to complete the image upload

In the previous course management module, we wrote a picture upload, so we can copy it
Image upload only needs to echo the image information, and the image information is directly stored in the corresponding path of the server without passing through the database, so it only needs the Web layer
The same is true of the course management module
Web tier: add some promotionadcontrollers:
 /*
   Advertisement picture upload
    */
    @RequestMapping("/PromotionAdUpload")
    public ResponseResult PromotionAdUpload(@RequestParam("file") MultipartFile file, 
                                            HttpServletRequest request) throws IOException {

        //Judge whether the received uploaded file is empty
        //file.isEmpty() determines whether the corresponding data is empty
        if (file.isEmpty()) {
            throw new RuntimeException();
            //Actively throw an exception instead of executing the corresponding exception information (such as try) after the exception occurs
            //Of course, when using this method, you also need to deal with exceptions accordingly
        }

        //Get project deployment path
        //D:\apache-tomcat-8.5.56\webapps\ssm_web\
        String realPath = request.getServletContext().getRealPath("/");
        //D:\apache-tomcat-8.5.56\webapps\
        String substring = realPath.substring(0, realPath.indexOf("ssm_web"));

        //Get original file name
        //Such as Lagou jpg
        String originalFilename = file.getOriginalFilename();
        //Make the file names basically not duplicate, and a user can hardly have the same name
        //There may be multiple users, but users cannot access each other, so here is equivalent to setting the file name not to be repeated
        String newFileName = System.currentTimeMillis() + 
            originalFilename.substring(originalFilename.lastIndexOf("."));
        //Get the suffix and use the timestamp as the name
        //Such as 1651975001568 jpg

        //Start file upload
        // D:\apache-tomcat-8.5.56\webapps\ upload\
        //Note: when \ u appears in the comment, there must be several, otherwise an error will be reported, so I added a space between \ and u above
        //\u is an escape character, which means that it is followed by a hexadecimal number. Specify a character through this hexadecimal number. If it is not, an error will be reported
        String uploadPath = substring + "upload\\";
        //It is also possible to add / but in order to symbolize the directory of windows, use \ \, and the web page is/
        File file1 = new File(uploadPath, newFileName);

        //If the directory does not exist, create the directory (judge whether there is a parent path uploadPath, and create if there is no parent path)
        if (!file1.getParentFile().exists()) {
            file1.getParentFile().mkdirs();
            System.out.println("Create directory" + file1);
        }

        //Upload pictures
        file.transferTo(file1);

        //Return the file name and file path to the front end, so that the front end displays pictures
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("fileName", newFileName);
        //File name, such as 1651975001568 jpg
        objectObjectHashMap.put("filePath", "http://localhost:8080/upload/" + newFileName);
        //The access path on the server, that is, the path to access server resources through the port

        ResponseResult responseResult = new ResponseResult(true, 200, "Picture uploaded successfully", 
                                                           objectObjectHashMap);

        return responseResult; //The collection will be parsed, that is, the map will be parsed



    }
Test interface using Postman
Next, we can create and modify advertisements. If we can, we can write them without looking at the following code
New advertisement
requirement analysis
Click the new button to save the requirements to the database page

Dao layer: add some PromotionAdMapper:
/*
    Add ad
     */
    public void savePromotionAd(PromotionAd promotionAd);
Add some promotionadmapper xml:
  <!--Add ad-->

    <insert id="savePromotionAd" parameterType="PromotionAd">
        INSERT INTO promotion_ad
        VALUES(NULL,#{name},#{spaceId},#{keyword},
         #{htmlContent},#{text},#{link},#{startTime},#{endTime},#{createTime},
         #{updateTime},#{status},#{priority},#{img});
<!--
Note: the type and format of some time fields are set in the class using annotations. You can go to the class and have a look
 When adding, it is best to add according to the corresponding format, otherwise an error is basically reported
-->
    </insert>
Service layer: add some PromotionAdService and its implementation classes:
    /*
    Add ad
     */
    public void savePromotionAd(PromotionAd promotionAd);
 //Add ad
    @Override
    public void savePromotionAd(PromotionAd promotionAd) {

        //Complete the information. Here we can say why we need to complete the information in the background
        //First, we need to get the time data from the front-end. If we add information directly to the front-end, we need to add several more parameters
        //The back-end only needs the set method, which is obviously more convenient, but no matter which one, it is the operation of information
        //And easy to use, that is, maintainability
        //Also try to be as good as possible (of course, it can be bad, or deliberately bad. It depends on how you operate, hey hey)
        Date date = new Date();
        promotionAd.setCreateTime(date);
        promotionAd.setUpdateTime(date);

        promotionAdMapper.savePromotionAd(promotionAd);
    }
Web tier: add some promotionadcontrollers:
 /*
    Add advertisements and modify and extend them later
     */
    @RequestMapping("/saveOrUpdatePromotionAd")
    public ResponseResult saveOrUpdatePromotionAd(@RequestBody PromotionAd promotionAd){

        promotionAdService.savePromotionAd(promotionAd);
        ResponseResult responseResult = new ResponseResult(true, 200, "Advertisement added successfully", null);
        return responseResult;
    }
Test interface using Postman
Next, let's modify
But before modifying, we need to echo
Dao layer: add some PromotionAdMapper:
/*
    Query advertisement by id
     */
    public PromotionAd findPromotionAdById(Integer id);
Add some promotionadmapper xml:
  <!--according to id Query advertisement-->
    <select id="findPromotionAdById" resultType="PromotionAd">
            select * from promotion_ad where id=#{id}
    </select>
Service layer: add some PromotionAdService and its implementation classes:
/*
    Query advertisement by id
     */
    public PromotionAd findPromotionAdById(Integer id);
  /*
    Query advertisement by id
     */
    @Override
    public PromotionAd findPromotionAdById(Integer id) {
        PromotionAd promotionAdById = promotionAdMapper.findPromotionAdById(id);

        return promotionAdById;
    }
Web tier: add some promotionadcontrollers:
 /*
    Query advertisement by id
     */
    @RequestMapping("/findPromotionAdById")
    public ResponseResult findPromotionAdById(Integer id){

        PromotionAd promotionAdById = promotionAdService.findPromotionAdById(id);

        ResponseResult responseResult = new ResponseResult(true, 200, "Successful query of specific advertisements", 
                                                           promotionAdById);
        return responseResult;
    }
Modify after echo
Dao layer: add some PromotionAdMapper:
  /*
   Modify advertisement
    */
    public void updatePromotionAd(PromotionAd promotionAd);
Add some promotionadmapper xml:
    <!--Modify advertisement-->
    <update id="updatePromotionAd" parameterType="PromotionAd">
        update promotion_ad
           <trim prefix="SET" suffixOverrides=",">
             <if test="name != null and name != ''">
               name = #{name},
             </if>
             <if test="spaceId != null and spaceId != ''">
               spaceId = #{spaceId},
             </if>
             <if test="link != null">
               link=#{link},
             </if>
             <if test="status != null and status != '' or status == 0">
            <!--
		Here's why the corresponding integer can be judged'',This is because the corresponding information will be changed into a string before replacement
		Therefore, no matter what the corresponding type is, it is the value comparison between strings
		-->
               status=#{status},
             </if>
             <if test="img != null">
               img=#{img},
             </if>
             <if test="text != null">
               text=#{text},
             </if>
             <if test="startTime != null">
               startTime=#{startTime},
             </if>
             <if test="endTime != null">
               endTime=#{endTime},
             </if>
             <if test="updateTime != null">
               updateTime=#{updateTime},
             </if>
           </trim>
           <where>
             <if test="id != null and id != '' ">id = #{id}</if>
           </where>

    </update>
Service layer: add some PromotionAdService and its implementation classes:
 /*
 Modify advertisement
  */
    public void updatePromotionAd(PromotionAd promotionAd);
    /*
 Modify advertisement
  */
    @Override
    public void updatePromotionAd(PromotionAd promotionAd) {
        promotionAd.setUpdateTime(new Date());

        promotionAdMapper.updatePromotionAd(promotionAd);

    }
Web layer: modify some PromotionAdController (extend saveOrUpdatePromotionAd method):
  @RequestMapping("/saveOrUpdatePromotionAd")
    public ResponseResult saveOrUpdatePromotionAd(@RequestBody PromotionAd promotionAd){
        ResponseResult responseResult;
        if(promotionAd.getId() == null) {
            promotionAdService.savePromotionAd(promotionAd);
            responseResult= new ResponseResult(true, 200, "Advertisement added successfully", null);

        }else{
            promotionAdService.updatePromotionAd(promotionAd);
            responseResult= new ResponseResult(true, 200, "Advertisement modified successfully", null);

        }
        return responseResult;
    }
Advertising status online and offline
requirement analysis
Requirement: click the button to realize the dynamic online and offline of the status

Dao layer: add some PromotionAdMapper:
/*
    Advertising dynamic online and offline
     */
    public void updatePromotionAdStatus(PromotionAd promotionAd);
Add some promotionadmapper xml:
 <!--Advertising dynamic online and offline-->   
    <update id="updatePromotionAdStatus" parameterType="PromotionAd">
        update promotion_ad set status = #{status},updateTime = #{updateTime} where id = #{id}
    </update>
Service layer: add some PromotionAdService and its implementation classes:
 /*
    Advertising dynamic online and offline
     */
    public void updatePromotionAdStatus(Integer id, Integer status);
    //Here we explain that the reason why we use classes in dao layer is mainly because of sql statements. It is convenient to use analogy and use multiple parameters
    //Since the parameters are basically not modified here, we set the fixed parameters to save a little memory space
    //The findAllPromotionAdByPage method parameter is a class, which is mainly used to prevent the sudden need for other parameters from making modification troublesome
    //Therefore, when it is determined that other parameters will be added, use class to operate and improve maintainability (when a small amount is increased, it takes precedence over maintainability)
    //Small amount: it is a very small promotion
 /*
   Advertising dynamic online and offline
    */
    @Override
    public void updatePromotionAdStatus(Integer id, Integer status) {
        PromotionAd promotionAd = new PromotionAd();
        promotionAd.setId(id);
        promotionAd.setStatus(status);
        promotionAd.setUpdateTime(new Date());
        promotionAdMapper.updatePromotionAdStatus(promotionAd);
    }
Web tier: add some promotionadcontrollers:
    /*
   Advertising dynamic online and offline
    */
    @RequestMapping("/updatePromotionAdStatus")
     public ResponseResult updatePromotionAdStatus(Integer id,Integer status){
         promotionAdService.updatePromotionAdStatus(id,status);
        ResponseResult responseResult = new ResponseResult(true, 200, "Advertising dynamic online and offline success", null);
        return responseResult;

     }
Test interface using Postman
User management module:
Function analysis of user management module:
Realize the following functions:
User paging and conditional query work together
User status settings
The following is also related to user operations, but it will be related to permissions. Therefore, after we explain the permission management module, we can operate in the corresponding code of the user:
Login (authority management module)
Permission control (operation of display management module, permission management module)
Assign roles (rights management module)
The login page displays:

The following are the module permissions that users can operate. If there is no corresponding permission, the corresponding module will not appear

The corresponding database table is found in the blog in Chapter 70 (actually contains all databases)
Table relationship introduction:

Implementation of user management module:
Operation of user paging and conditional query
To return the overall data is actually to perform conditional query first and then paging. Different from the paging of the previous advertisement, this is when querying
That is, conditional statements and paging statements are added, while only paging statements are added in advertisements
requirement analysis
Requirements: realize multi condition paging combined query

Specific analysis:

According to the analysis, we know that we need to write a class, and the reason why we don't extend the PromotionAdVo class is because it is extended
Although the corresponding memory space is dominant now, with more requests for advertisement paging, there are more and more initializations (two variables become five variables)
Therefore, the larger the object is created, the more memory space is required. In the long run, it is better to create a new class
Create UserVo class:
package com.lagou.domain;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 *
 */
public class UserVo {
    private Integer currentPage;
    private Integer pageSize;
    //Multi condition query: user name (mobile number)
    private String username;
    //Registration start time
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    //After using this, spring MVC will only operate this annotation to obtain the corresponding Date type, instead of using the default two transformations (Methods)
    //As long as it is a string, it basically needs to be converted to Date type
    private Date startCreateTime;
    //Registration end time
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    /*
    Using annotations is the same as the configuration file, but annotations do not need to be activated
 That is < MVC: annotation driven conversion service = "conversionservice" > < / MVC: annotation driven >
Conversion service = "conversionservice" is not configured

    The configuration file specifies the corresponding class, and the annotation directly specifies the corresponding type in this class
    And carry out the operation of type conversion through annotation content (with method call), so the principle is similar to xml, but the bottom layer calls it for us
    */
    private Date endCreateTime;

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getStartCreateTime() {
        return startCreateTime;
    }

    public void setStartCreateTime(Date startCreateTime) {
        this.startCreateTime = startCreateTime;
    }

    public Date getEndCreateTime() {
        return endCreateTime;
    }

    public void setEndCreateTime(Date endCreateTime) {
        this.endCreateTime = endCreateTime;
    }
}

Dao layer: UserMapper:
package com.lagou.dao;

import com.lagou.domain.User;
import com.lagou.domain.UserVo;

import java.util.List;

/**
 *
 */
public interface UserMapper {
    /*
    User paging and multi condition combination query
     */
    public List<User> findAllUserByPage(UserVo userVo);
}

Corresponding mapping configuration file (UserMapper.xml):
<?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.lagou.dao.UserMapper">
    <!--User paging and multi condition combination query-->
    <select id="findAllUserByPage" parameterType="UserVo" resultType="User">
        select * from user
        <where>
            <if test="true">
                and is_del !=1
            </if>
            <if test="username !=null and username != ''">
            <!--
            Because the string will recognize''Operation, rather than string recognition''When, it is generally the default
            So strings usually need to be judged'',Other types are generally not required
            -->
                and name = #{username}  <!-- Fuzzy query is not performed here -- >
            </if>
            <if test="startCreateTime !=null and endCreateTime != null">
                and create_time between #{startCreateTime} and #{endCreateTime}
            </if>
        </where>
    </select>
</mapper>
Service layer: UserService and its implementation class:
package com.lagou.service;

import com.github.pagehelper.PageInfo;
import com.lagou.domain.UserVo;

/**
 *
 */
public interface UserService {
    /*
    User paging and multi condition query
     */

    public PageInfo findAllUserByPage(UserVo userVo);
    //As mentioned earlier, the return value type contains both the information required for paging and the corresponding query result information (usually a list set)
}

package com.lagou.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lagou.dao.UserMapper;
import com.lagou.domain.User;
import com.lagou.domain.UserVo;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    //User paging and multi condition query
    @Override
    public PageInfo findAllUserByPage(UserVo userVo) {

        //Paging settings
        PageHelper.startPage(userVo.getCurrentPage(),userVo.getPageSize());

        List<User> allUserByPage = userMapper.findAllUserByPage(userVo);
        PageInfo<User> pageInfo = new PageInfo<>(allUserByPage);
        return pageInfo;
    }
}

Web tier: UserController:
package com.lagou.controller;

import com.github.pagehelper.PageInfo;
import com.lagou.domain.ResponseResult;
import com.lagou.domain.UserVo;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /*
    User paging and multi condition query
     */
    @RequestMapping("/findAllUserByPage")
    public ResponseResult findAllUserByPage(@RequestBody UserVo userVo) {

        PageInfo allUserByPage = userService.findAllUserByPage(userVo);
        ResponseResult responseResult = new ResponseResult(true, 200, "Paging multi condition query succeeded", 
                                                           allUserByPage);
        return responseResult;
    }
}

Test interface using Postman
User status settings:
Through the above writing, if you can, you can modify the user status setting by yourself without looking at the following code
requirement analysis
Click disable to change the user's status
Dao layer: add some UserMapper:
 /*
    User status modification
     */
    public void updateUserStatus(User user);
Add some usermapper xml:
  <!--User status settings-->
    <update id="updateUserStatus" parameterType="User">
            update user set status = #{status},update_time = #{update_time} where id = #{id}
    </update>
Service layer: add some UserService and its implementation classes:
  /*
   User status modification
    */
    public void updateUserStatus(Integer id,String status);
 /*
       User status modification
        */
    @Override
    public void updateUserStatus(Integer id,String status) {

        User user = new User();
        user.setId(id);
        user.setStatus(status);
        user.setUpdate_time(new Date());

        userMapper.updateUserStatus(user);


    }
Web layer: add some usercontrollers:
  /*
    User status modification
     */
    @RequestMapping("/updateUserStatus")
    public ResponseResult updateUserStatus(Integer id,String status) {
        userService.updateUserStatus(id,status);
        ResponseResult responseResult = new ResponseResult(true, 200, "User status modified successfully",status);
        return responseResult;
    }
Test interface using Postman

Tags: Java SSM

Posted by amrigo on Thu, 19 May 2022 22:51:48 +0300