mybatis中的模糊查询
模糊查询被我们片面的理解为只有一种,其实模糊查询查询包括左模糊查询,右模糊查询和整个模糊查询
左模糊查询:
/**
* 左模糊查询
* @param student
* @return
*/
public List<Student> findSomeStudent(Student student);
<!--左模糊查询-->
<select id="findSomeStudent" resultType="student">
SELECT *from Student WHERE name LIKE '' #{name } '%' AND age>#{age}
</select>
/**
* 左模糊查询
*/
@Test
public void find() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sf.openSession();
IStudentDAO mapper = session.getMapper(IStudentDAO.class);
Student student=new Student();
student.setName("飞");
student.setAge(20);
List<Student> students = mapper.findSomeStudent(student);
for (Student item :students){
System.out.println(item.getName());
}
//提交事务
session.commit();
//关闭会话,释放资源
session.close();
}
右模糊查询
/**
* 右模糊查询
* @param student
* @return
*/
public List<Student> findSomeStudent(Student student);
<!--右模糊查询-->
<select id="findSomeStudent" resultType="student">
SELECT *from Student WHERE name LIKE '%' #{name } '' AND age>#{age}
</select>
/**
* 右模糊查询
*/
@Test
public void find() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sf.openSession();
IStudentDAO mapper = session.getMapper(IStudentDAO.class);
Student student=new Student();
student.setName("张");
student.setAge(20);
List<Student> students = mapper.findSomeStudent(student);
for (Student item :students){
System.out.println(item.getName());
}
//提交事务
session.commit();
//关闭会话,释放资源
session.close();
}
整个模糊查询
/**
* 整个模糊查询
* @param student
* @return
*/
public List<Student> findSomeStudent(Student student);
<!--整个模糊查询-->
<select id="findSomeStudent" resultType="student">
SELECT *from Student WHERE name LIKE '%' #{name } '%' AND age>#{age}
</select>
/**
* 整个模糊查询
*/
@Test
public void find() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sf.openSession();
IStudentDAO mapper = session.getMapper(IStudentDAO.class);
Student student=new Student();
student.setName("张");
student.setAge(20);
List<Student> students = mapper.findSomeStudent(student);
for (Student item :students){
System.out.println(item.getName());
}
//提交事务
session.commit();
//关闭会话,释放资源
session.close();
}
模糊查询的sql语句三种形式
前二种不会引起sql注入,第三种会引起sql注入
SELECT *from Student WHERE name LIKE concat('%',#{name },'%' AND age>#{age})
SELECT *from Student WHERE name LIKE '%' #{name } '%' AND age>#{age}
SELECT *from Student WHERE name LIKE '%${name}%' AND age>#{age}