MyBatis怎么使用动态表名(#和$的区别)

MyBatis怎么使用动态表名(#和$的区别)

一、需求描述

将对不同的表对象进行的一系列相同的操作存在同一个表中
在生成操作的同时也要改变某个表中的某一项数据

举个例子:
对动态、博客、空间啥的查看、点赞、收藏等操作
就需要在对应的表中进行数据修改
同时也需要在操作表中记录是对哪种对象进行的什么操作

二、实现

对某一个对象的点赞操作

Action.class

public class Action {
    
    
    private int id;
    private String account;
    private int actionId;
    private String type;
    private String actionType;
    private String actionTime;

    public Action(String account, int actionId, String type, String actionType, String actionTime) {
    
    
        this.account = account;
        this.actionId = actionId;
        this.type = type;
        this.actionType = actionType;
        this.actionTime = actionTime;
    }

    public Action() {
    
    

    }
}

ActionMapper.xml

<update id="thumbsUp" parameterType="Action">
     UPDATE ${type}
     SET thumbsupcount = thumbsupcount + 1
     WHERE #{actionId} = id
</update>

action表结构

在这里插入图片描述

三、原理

主要是MyBatis中对于xml文件的参数传入机制中#和$的区别:
1、#传入的参数在SQL中显示为字符串(当成一个字符串),会对自动传入的数据加一个双引号,所以使用#解析type就会抛出sql语句有误的的错误

2、$传入的参数在SqL中直接显示为传入的值,所以可以直接解析成sql语句

猜你喜欢

转载自blog.csdn.net/wobuxiangxin1314/article/details/127711525
今日推荐