- 使用userMapper.xml中<select>标签的parameterType参数可以实现sql语句的预赋值,防止sql注入
参数查询
- UsersMapper.java
public interface UsersMapper {
public Users getUserListById(int id);
}
- UsersMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
<mapper namespace="com.mybatis.dao.UsersMapper">
<select id="getUserById" parameterType="int" resultType="Users">
select * from smbms_user where
id=#{id}
</select>
…
</mapper>
- Test.java
@Test
public void testGetUserList() {
SqlSession sqlSession=null;
try{
sqlSession=MyBatisUtil.createSqlSession();
Users user=sqlSession.getMapper(UsersMapper.class).getUserById();
logger.debug("UserMappingTest count--->"+user.getUserName());
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
模糊查询
- UsersMapper.java
public interface UsersMapper {
public List<Users> getUserListByUserName(String userName);
}
- UsersMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
<mapper namespace="com.mybatis.dao.UsersMapper">
<select id="getUserList" parameterType="String" resultType="Users">
select * from smbms_user where userName like CONCAT('%',#{userName},'%')
</select>
…
</mapper>
- Test.java
@Test
public void testGetUserList() {
SqlSession sqlSession=null;
List<Users> userList =new ArrayList<Users>();
try{
sqlSession=MyBatisUtil.createSqlSession();
userList=sqlSession.getMapper(UsersMapper.class).getUserListByUser("张");
}catch(Exception e){
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
for(Users user:userList) {
System.out.println(user.getUserName());
}
}