1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Mybatis映射文件SQL语句模糊查询 #和$的区别和注意事项

Mybatis映射文件SQL语句模糊查询 #和$的区别和注意事项

时间:2019-02-08 09:38:47

相关推荐

Mybatis映射文件SQL语句模糊查询 #和$的区别和注意事项

Mybatis映射文件SQL语句模糊查询

1. “%”#{value}"%" 在参数中不需要添加 %_ 推荐使用

2. ‘%${value}%’ 在参数中不需要添加 %_

3. #{abc} 在参数中添加 %_

#和$的区别和注意事项

${}直接拼接 ,不会转换类型

如果是简单类型,必须写${value}如果是pojo类型,${属性名}(注意:需要转换类型)

#{}相当于占位符,可以自动的转换类型 可以防止SQL注入

如果是简单类型,可以随便写${随便写}如果是pojo类型,${属性名}(注意:可以自动转换类型)

一、# “%”#{value}"%"

1.UserMapper.xml

<select id="findByUsername" parameterType="java.lang.String" resultType="com.william.domain.User">select * from user where username like "%"#{value}"%"</select>

2.TestMybatis

/*** 模糊查询* 通过用户名字模糊查询*/@Testpublic void findByUsername(){InputStream inputStream = Resources.class.getClassLoader().getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> selectList = sqlSession.selectList("com.william.mapper.UserMapper.findByUsername","a");for (Object o : selectList) {System.out.println(o);}sqlSession.close();}

3.测试结果

执行的SQL语句

Preparing: select * from user where username like "%"?"%" Parameters: a(String)

二、$ ‘%${value}%’

1.UserMapper.xml

<!--模糊查询--><select id="findByUsername" parameterType="java.lang.String" resultType="com.william.domain.User">select * from user where username like '%${value}%'</select>

2.TestMybatis

/*** 模糊查询* 通过用户名字模糊查询*/@Testpublic void findByUsername(){InputStream inputStream = Resources.class.getClassLoader().getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> selectList = sqlSession.selectList("com.william.mapper.UserMapper.findByUsername","a");for (Object o : selectList) {System.out.println(o);}sqlSession.close();}

3.测试结果

执行的SQL语句

Preparing: select * from user where username like '%a%' Parameters:

三、在测试类参数中添加

1.UserMapper.xml

<select id="findByUsername" parameterType="java.lang.String" resultType="com.william.domain.User">select * from user where username like #{abc}</select>

2.TestMybatis

/*** 模糊查询* 通过用户名字模糊查询*/@Testpublic void findByUsername(){InputStream inputStream = Resources.class.getClassLoader().getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> selectList = sqlSession.selectList("com.william.mapper.UserMapper.findByUsername","%a%");for (Object o : selectList) {System.out.println(o);}sqlSession.close();}

3.测试结果

执行的SQL语句

Preparing: select * from user where username like ? Parameters: %a%(String)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。