myBatis模糊查找

来源:互联网 发布:不是我不爱你网络歌手 编辑:程序博客网 时间:2024/05/21 04:40

对数据库条件查找,进行姓名模糊查找,我使用的是mysql数据库
正常语句:select * from student where 1=1 and name like ‘%name%’;
蓝色name是从service层得到的名字,即需要模糊查找的内容,这里要注意模糊查找格式:like ‘%查找的内容%’


方法一、在xml中对模糊查找的处理
下面是myBatis.xml文件中对模糊查找的配置语句

<!--条件查找、模糊查询,如果名字不为空对名字进行模糊查找 --><select id="findByCondition" resultType="com.wql.Student"        parameterType="com.wql.Student">        select * from student where 1=1        <if test="name!=null">            and name like '%${name}%'        </if>    </select>

上面的处理方式是在xml中对模糊查找的处理,格式为:‘%${name}%’
这里必须是$符号,要原样输出,不可以为#号。


方法二、在处理层解决

public class TestEnd {    public static void main(String[] args) {        ServiceDao sd=new ServiceDaoImpl();        //sd.add(new Student(7,"殇滘",21,"男"));        //模糊查找        List<Student> list=sd.findByCondition(new Student(7,"'%王%'",21,"男"));        System.out.println(list);        List<Student> listAll=sd.findAll();        System.out.println(listAll);    }}

List list=sd.findByCondition(new Student(7,”’%王%’”,21,”男”));
直接在传入数据时对姓名处理,格式:‘%王%’
这种处理方式在xml文件中就不要方法一那种写法了

<!--条件查找、模糊查询,如果名字不为空对名字进行模糊查找 -->    <select id="findByCondition" resultType="com.wql.Student"        parameterType="com.wql.Student">        select * from student where 1=1        <if test="name!=null">            and name like ${name}        </if>    </select>

方法三、在myBatis的DbUtils的数据库具体操作实现层处理
这里写图片描述

public List<Student> findByCondition(Student s) {        String name=s.getName();//得到姓名        s.setName("'%"+name+"%'");//模糊查找格式处理        String namespace="com.studentDao.ServiceDao";        SqlSession sqlSession=MyBatisUtils.getSqlSession();        return sqlSession.selectList(namespace+".findByCondition", s);    }
String name=s.getName();//得到姓名s.setName("'%"+name+"%'");//模糊查找格式处理

处理方式,先得到姓名,在对姓名进行处理格式


上面三种方式推荐使用第一种和第二种方式,因为这两种方式是一劳永逸的,
我个人喜欢第一种方式