tyboot simple function demonstration without sql encoding

tyboot simple function demonstration without sql encoding

tybootdemo source

https://gitee.com/magintursh/tybootdemo

tyboot source:

https://gitee.com/magintursh/tyboot

https://github.com/magintursh/tyboot

Example project interface screenshot

The following are the interface features for this demonstration to demonstrate simple tyboot-based encoding

Posman interface documentation: https://documenter.getpostman.com/view/29857/SzmY8gBk?version=latest

No sql encoding experience

Mainly a simple code demonstration of the service layer, the orm layer mapper is just an empty interface, it is not necessary to define a method, so almost all the time the code just needs to write the service layer's classes.

The service class in the sample project has no interfaces and only an implementation class, which will be discussed later.

controller

@RestController
@TycloudResource(module = "demo", value = "demo")
@RequestMapping(value = "/v1/demo")
@Api(tags ="demo-Example")
public class TybootDemoResource {

    @Autowired
    private PublicUserInfoService publicUserInfoService;

    @TycloudOperation(ApiLevel = UserType.PUBLIC,needAuth = false)
    @ApiOperation(value = "Create data")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseModel<PublicUserInfoModel> createUser(@RequestBody PublicUserInfoModel model) throws Exception {
        if(ValidationUtil.isEmpty(model) || ValidationUtil.isEmpty(model.getMobile()))
            throw new BadRequest("Data verification failed.");
        RequestContext.setExeUserId("system");//No user authentication, no current user information, manually fill.
        return ResponseHelper.buildResponse(publicUserInfoService.createUser(model));
    }

    @TycloudOperation(ApiLevel = UserType.PUBLIC,needAuth = false)
    @ApiOperation(value = "Update Data")
    @RequestMapping(value = "/{userId}", method = RequestMethod.PUT)
    public ResponseModel<PublicUserInfoModel> updateUser(@PathVariable("userId") String  userId,@RequestBody PublicUserInfoModel model) throws Exception {
        RequestContext.setExeUserId("system");//No user authentication, no current user information, manually fill.
        model.setUserId(userId);
        return ResponseHelper.buildResponse(publicUserInfoService.updateUser(model));
    }

    @TycloudOperation(ApiLevel = UserType.PUBLIC,needAuth = false)
    @ApiOperation(value = "Query a single data object")
    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public ResponseModel<PublicUserInfoModel> queryByUserId(@PathVariable("userId") String  userId) throws Exception {
        return ResponseHelper.buildResponse(publicUserInfoService.queryByUserId(userId));
    }

    @TycloudOperation(ApiLevel = UserType.PUBLIC,needAuth = false)
    @ApiOperation(value = "Query Data List")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseModel<List<PublicUserInfoModel>> queryByAgencyCode(@RequestParam("agencyCode") String  agencyCode) throws Exception {
        return ResponseHelper.buildResponse(publicUserInfoService.queryByAgencyCode(agencyCode));
    }

    @TycloudOperation(ApiLevel = UserType.PUBLIC,needAuth = false)
    @ApiOperation(value = "Paging Query Data List")
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public ResponseModel<Page<PublicUserInfoModel>> queryUserPage(
            @RequestParam(value = "agencyCode",required = false) String  agencyCode,
            @RequestParam(value = "nickName",required = false) String  nickName,
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size) throws Exception {
        Page<PublicUserInfoModel> page = new Page(current,size);
        return ResponseHelper.buildResponse(publicUserInfoService.queryUserPage(page,agencyCode,nickName));
    }
}

The method ResponseHelper.buildResponse() returns a uniform data format as follows:

{
    "status": 200,  //Status code, same as http return code
    "result": null,//Result object
    "traceId": "1255684406704324610",//Request Number
    "devMessage": "SUCCESS",//Error messages, for developers to see, may have error stacks output here
    "message": "", //The information used to prompt the user is normally empty, otherwise there is an error message
    "path": "/v1/demo"   //Path to this request
}

service

Demonstrating encoding in service, a simple sql-free encoding experience, BaseService has encapsulated many generic methods that you can choose to use.

About caching:

Creating data updates Data query data has cached methods that can be used to complete cache updates and keep the cache synchronized with mysql.Simple data caching, complex business function-related caching, or manual processing is appropriate here.

About mapper:

There is no reference to the mapper interface, no xml defined, and no SQL written.Simply write down the following methods to accomplish the basic functions of a module.(Actually, the code generation section can already generate the following methods). The mapper is just an empty interface, not necessary, and does not need to define methods in it.Defining methods in complex report queries is not considered unless they must write sql.

@Service
public class PublicUserInfoService extends BaseService<PublicUserInfoModel, PublicUserInfo, PublicUserInfoMapper> {

    /**
     * Create data
     * Save directly to the relational database using the methods provided by BaseService or at the same time to redis based on the business primary key
     */
    public PublicUserInfoModel createUser(PublicUserInfoModel model) throws Exception
    {
        //Temporary userId initialization
        String userId = Sequence.generatorSmsVerifyCode6();
        model.setUserId(userId);
        model.setCreateTime(new Date());
        model.setAgencyCode(CoreConstans.CODE_SUPER_ADMIN);
        //Save to the database and press the business primary key userId to cache, and delete the list data cached by agencyCode. If the business primary key is not filled in, the physical primary key is cached by default
        //return this.createWithCache(model,model.getUserId(),genCacheKeyForModelList(model.getAgencyCode()));

        // Save directly to database
        return createWithModel(model);
    }

    /**
     * Update data based on physical primary key
     * Save directly to a relational database using the methods provided by BaseService or simultaneously update objects to redis based on business primary keys
     */
    public PublicUserInfoModel updateUser(PublicUserInfoModel model) throws Exception
    {
        //Save to the database, update the cache by the business primary key userId, and delete the list data cached by agencyCode.
        //this.updateWithCache(model,model.getUserId(),genCacheKeyForModelList(model.getAgencyCode()));

        //Save directly to database
        return this.updateWithModel(model);
    }

    /**
     * Query a single object conditionally
     * The method parameter name needs to be kept constant with the property name defined in the Public UserInfoModel.
     *  To use the queryModelByParamsWithCache and queryModelByParams methods.
     *  The order of method parameters invoked should be the same as the current method parameter order.
     */
    public PublicUserInfoModel queryByUserId(String userId) throws Exception
    {
        //Query a single object and cache the results by parameters, and get the same parameters directly from the cache the next time.
        //this.queryModelByParamsWithCache(userId);

        return this.queryModelByParams(userId);
    }

    /**
     * Query the list by condition, and sort it backwards by creation time
       The parameter order of the called method needs to be kept i constant with the current method 
     */
    public List<PublicUserInfoModel> queryByAgencyCode(String agencyCode) throws Exception
    {
        //Cache query results by parameter Direct read cache next time same parameter
        //this.queryForListWithCache("CREATE_TIME",false,agencyCode);

        //Query top list
        //this.queryForTopList(10,"CREATE_TIME",false,agencyCode);

        return this.queryForList("CREATE_TIME",false,agencyCode);
    }

    /**
     * By conditional paging queries, the order of parameters of the called method needs to remain i with the current method 
     */
    public Page<PublicUserInfoModel> queryUserPage(Page<PublicUserInfoModel> page,String agencyCode,@Condition(Operator.like) String nickName) throws Exception
    {
        return this.queryForPage(page,"CREATE_TIME",false,agencyCode,nickName);
    }

}

About note @Condition:

The logical relationship definition of the user query parameter, which is and by default, is determined internally using the mybatisplus condition.Encapsulated conditions see the definition in class org.typroject.tyboot.core.rdbms.annotation.Operator

Here is the code for VO Po and mapper

mapper :

public interface PublicUserInfoMapper extends BaseMapper<PublicUserInfo> {

}

model:

package org.typroject.tyboot.demo.face.model;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;

import java.util.Date;

@EqualsAndHashCode(callSuper = true)
@Data
public class PublicUserInfoModel extends BaseModel {

    private static final long serialVersionUID = 1L;

    private String userId;
    private String agencyCode;
    private String nickName;
    private String mobile;
    private String gender;
    private Date createTime;
    private Integer userAge;
    private String email;
}

entity:

package org.typroject.tyboot.demo.face.orm.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;

import java.util.Date;

@EqualsAndHashCode(callSuper = true)
@Data
@TableName("public_user_info")
public class PublicUserInfo extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @TableField("USER_ID")
    private String userId;
    @TableField("AGENCY_CODE")
    private String agencyCode;
    @TableField("NICK_NAME")
    private String nickName;
    @TableField("MOBILE")
    private String mobile;
    @TableField("GENDER")
    private String gender;
    @TableField("CREATE_TIME")
    private Date createTime;
    @TableField("USER_AGE")
    private Integer userAge;
    @TableField("EMAIL")
    private String email;
}

No sql encoding is only relative.The current implementation is for the processing of form operations.Business that can be handled with a single form does not have to use sql that is too complex to handle business problems.The benefits of easy caching of form operations, easy subsequent database splitting, and so on.

Tags: Programming SQL Database encoding Lombok

Posted on Tue, 05 May 2020 03:38:28 -0700 by ukphoto