mybatis入门使用5:传入表名作参数

本文介绍了如何在MyBatis中将表名作为参数进行动态SQL操作。通过设置`statementType="STATEMENT"`并在XML映射文件中使用`${tableName}`来实现动态传入表名。示例代码展示了一个使用HashMap传递参数到mapper方法进行计数查询的单元测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用mybatis时有时会使用表名作参数:

1、动态传入表名做参数, 在xml 中 加入 statementType="STATEMENT",使用$ ${tableName},
2、此时需要使用map或者对象才能传入参数,单个参数提示没有get/set

<select id="selectCount" resultType="java.lang.Integer" parameterType="java.lang.String" statementType="STATEMENT">
select
Count(1)
from ${tableName}
</select>


package com.lls.test;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.lls.mapper.EmployeeMapper;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/spring-mybatis.xml" })
public class TableNameParamTest {

private static final Logger LOGGER = LoggerFactory.getLogger(TableNameParamTest.class);

@Autowired
private EmployeeMapper employeeMapper;

@Test
public void tableNameParamTest() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("tableName", "t_employee");
int count = employeeMapper.selectCount(map);
LOGGER.info("count " + count);
}
}

代码文档:http://download.youkuaiyun.com/download/lanlianhua_luffy/9869769




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值