sql元素: 用来定义可重用的 SQL 代码段,可以包含在其他语句中;
<sql id="Base_Column_List">
id, user_name, real_name, sex, mobile, email, note,
position_id
</sql>
参数:向sql语句中传递的可变参数
预编译 #{}:将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号,能够很大程度防止
sql注入;
传值 ${}:传入的数据直接显示生成在sql中,无法防止sql注入;
表名、选取的列是动态的,order by和in操作, 可以考虑使用$
<select id="selectBySymbol" resultMap="BaseResultMap">
select
#{inCol}
from ${tableName} a
where a.sex = #{sex}
order by ${orderStr}
</select>
测试类:
@Test
// 参数#和参数$区别测试()
public void testSymbol() {
// 2.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取对应mapper
TUserMapper mapper = sqlSession.getMapper(TUserMapper.class);
String inCol = "id, user_name, real_name, sex, mobile, email, note";
String tableName = "t_user";
Byte sex = 1;
String orderStr = "sex,user_name";
List<TUser> list = mapper.selectBySymbol(tableName, inCol, orderStr, sex);
System.out.println(list.size());
}