Ledger APP server development

Ledger APP development

study hard, improve every day

This article has been included in my Github warehouse DayDayUP: github.com/RobodLee/DayDayUP, welcome to Star, for more articles, please go to: Directory Navigation

In the last article, we talked about the development of the ledger APP client, this article will talk about the server-side development. There are two core functions of the server. One is to save the data from the client to the database. The database I chose is MySQL; the other is to query all the records of the specified user from the database and send it back to the client. This article mainly talks about these two functions. I won’t talk about the user registration and login functions. They are relatively simple. You can check my source code and click to view

1. Environment construction

The whole project is based on SpringBoot, so the configuration is relatively simple, I won't say much. Let me first talk about the design of my database tables. There are two tables in total, one is the user table for storing user information; the other is the record table for storing all records.

data sheet

I chose MyBatis as the framework of the persistence layer, so I need to add the dependencies required by MyBatis in pom.xml. There are three related to database interaction. One is the initial dependency of MyBatis, the other is the connection driver of MySQL, and the last is the field type mapping of MyBatis database. If there is no third, an error will be reported when storing Date.

    <dependencies>

        …………

        <!--mybatis起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <!-- MySQL连接驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>

        <!-- mybatis数据库字段类型映射 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-typehandlers-jsr310</artifactId>
            <version>1.0.1</version>
        </dependency>

        …………

    </dependencies>

Let's take a look at the realization of the function when the preparation is done.

2. Function realization

1. Implementation of upload function

1.1 Controller layer

    @RequestMapping("/uploadRecords")
    public ResultInfo<String> uploadRecords(String phoneNumber , String recordsJson) {
    
    
        ResultInfo<String> resultInfo = null;
        List<Record> records = JSONArray.parseArray(recordsJson , Record.class);
        try {
    
    
            resultInfo = recordService.uploadRecords(phoneNumber,records);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            resultInfo = new ResultInfo<>();
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("内部错误");
        }
        return resultInfo;
    }

The control layer receives two parameters, one is phoneNumber, which is used to determine the data passed by the user, and the other is the json string of List. When uploading on the client, I converted List to json, so I first need to convert Json to List again, and then call the recordService.uploadRecords method to pass the List in.

1.2 Service layer

    @Override
    public ResultInfo<String> uploadRecords(String phoneNumber, List<Record> records) throws Exception {
    
    
        for (Record record : records) {
    
    
            int status = record.getStatus();
            if (status == 1) {
    
      //添加数据
                System.out.println(record.toString());
                recordMapper.addRecord(phoneNumber, record);
            } else if (status == 2) {
    
       //删除数据
                recordMapper.deleteRecord(record.getUuid());
            } else if (status == 3) {
    
       //修改数据
                recordMapper.upgradeRecord(record);
            }
        }
        //如果在上面代码中出现了异常下面的代码就不会执行,直接将异常抛给Controller层处理
        ResultInfo<String> resultInfo = new ResultInfo<>();
        resultInfo.setFlag(true);
        resultInfo.setData("同步成功");
        return resultInfo;
    }

In the Service layer, traverse the passed List, select the appropriate operation according to the value of status, whether to add, delete or modify data, and then call the corresponding method of the dao layer. Let's take a look at what the Dao layer does.

1.3 Dao layers

    /**
     * 添加一条记录
     * @param phoneNumber
     * @param record
     * @throws  Exception
     */
    @Insert("insert into record(id,phoneNumber,category,content,money,status,date) " +
            "values (#{record.uuid},#{phoneNumber},#{record.category},#{record.content},#{record.money},0,#{record.date})")
    void addRecord(@Param("phoneNumber") String phoneNumber,@Param("record") Record record) throws Exception;

    /**
     * 删除指定的记录
     * @param recordId
     * @throws Exception
     */
    @Delete("DELETE FROM record WHERE id = #{recordId}")
    void deleteRecord(@Param("recordId")String recordId) throws Exception;

    /**
     * 修改服务器中的记录
     * @param record
     * @throws Exception
     */
    @Update("UPDATE record SET category=#{category},content=#{content},money=#{money},status=#{status},date=#{dateString} WHERE id = #{uuid}")
    void upgradeRecord(Record record) throws Exception;

It's very simple. We can add, delete, and modify data as long as we write the corresponding SQL statement. All other operations are done by MyBatis for us.

Having said the realization of uploading data, let's take a look at how to realize downloading data.

2. Realization of download function

2.1 Controller layer

    @RequestMapping("/downloadRecords")
    public ResultInfo<List<Record>> downloadRecords(String phoneNumber) {
    
    
        ResultInfo<List<Record>> resultInfo = null;
        try {
    
    
            resultInfo = recordService.downloadRecords(phoneNumber);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            resultInfo = new ResultInfo<>();
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("内部错误");
        }
        return resultInfo;
    }

The code of the Controller layer is very simple, that is, it receives a phoneNumber parameter to determine which user sent the request, and then calls the recordService.downloadRecords(phoneNumber) method to pass the phoneNumber in, and then nine comes to the Service layer.

2.2 Service layer

    @Override
    public ResultInfo<List<Record>> downloadRecords(String phoneNumber) throws Exception {
    
    
        List<Record> records = recordMapper.findAllByPhoneNumber(phoneNumber);
        //如果在上面代码中出现了异常下面的代码就不会执行,直接将异常抛给Controller层处理
        ResultInfo<List<Record>> resultInfo = new ResultInfo<>();
        resultInfo.setFlag(true);
        resultInfo.setData(records);
        return resultInfo;
    }

It is also very simple in the Service layer, that is, call the recordMapper.findAllByPhoneNumber(phoneNumber) method to get the List collection that is queried.

2.3 Dao layers

    /**
     * 根据手机号码查询该用户下所有的信息
     * @param phoneNumber
     * @throws Exception
     * @return
     */
    @Select("SELECT * FROM record WHERE phoneNumber = #{phoneNumber}")
    @Results({
    
    
            @Result(property = "uuid",column = "id",id = true),
            @Result(property = "category",column = "category"),
            @Result(property = "content",column = "content"),
            @Result(property = "money",column = "money"),
            @Result(property = "status",column = "status"),
            @Result(property = "date",column = "date")
    })
    List<Record> findAllByPhoneNumber(String phoneNumber) throws Exception;

The id field of the record in the database corresponds to the uuid attribute in the Record class. Why does the id correspond to the id directly? The reason I said in the last article is that the id of the client's SQLite can only be of int type, so a uuid attribute is added.

to sum up

The server side does not have any complicated functions, just some simple CRUD. I believe that you can follow the ideas in my article to understand my code.

WeChat public account

Guess you like

Origin blog.csdn.net/weixin_43461520/article/details/105476416