MyBatis动态传入WHERE子句表名和SELECT子句列名

文章来源:MyBatis动态传入WHERE子句表名和SELECT子句列名

 

要在项目中实现动态传入表名、列名,你需要将***Mapper.XML配置文件做如下修改:
1、添加属性statementType="STATEMENT"
备注:statementType:STATEMENT(非预编译)、PREPARED(预编译)或 CALLABLE中的任意一个
这就告诉 MyBatis 分别使用Statement(STATEMENT),PreparedStatement(PREPARED)或CallableStatement(CALLABLE)。默认:PREPARED。

2、将SQL语句里的所有变量取值都改成${xxxx},而不是#{xxx}
实例[mapper文件]:
java代码:
public interface TestMappper {
/**
* 获取指定表名指定列名的最大值
*/
public int getMaxValueForColumn(Map }

public class Test {
@Autowired
TestMappper testMappper;
public void getMaxVal() {
Map args = new HashMap();
args.put("tabName", "t_student");
args.put("id", "n_age");
int maxVal = testMappper.getMaxValueForColumn(args);
System.out.println("max age=" maxVal);
}
}

3、使用${xxxx}方式传入的数据直接显示生成在sql中,对于字符串数据,需要手动加上引号。如下:

 

 

你可能感兴趣的:(mybatis)