mybtis-mysql模糊查询

注意:
不同的数据库写法不一样!
mysql的写法是这样的:

concat('%',#{0},'%')

下面将主要步骤做一个记录:
Category.xml中新增以下语句:

        

稍完整配置约束如下:



    
        
    
书写TestMybatis.java
package com.how2java.pojo;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class TestMybatis { 
    public static void main(String[] args) throws IOException {
        String resource="mybatis-config.xml";
        InputStream inputStream=Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        
        List cs = sqlSession.selectList("listCategoryByName","cat");
        for (Category c : cs) {
            System.out.println(c.getName());
        }
        /*Category c=new Category();
        c.setName("新增加的Category");
        sqlSession.insert("addCategory",c);
        listAll(sqlSession);*/
        sqlSession.commit();
        sqlSession.close();
    }
    public static void listAll(SqlSession session) {
        List categories=session.selectList("listCategory");
        for (Category c : categories) {
            System.out.println(c.getName());
        }
    }
}

表结构如下:

mybtis-mysql模糊查询_第1张图片
表结构.PNG

测试结果:

category1
category2
新增加的Category


更加高级的写法如下(与本项目无关)

SELECT * FROM t_app  
          
              
                name like CONCAT('%','${name}','%' )  
              
              
                AND url like CONCAT('%','${url}','%' )  
              
          
        limit #{begin},${end}  

感谢以下两篇博文:

http://mxdba.iteye.com/blog/844748
http://how2j.cn/k/mybatis/mybatis-query/1107.html#nowhere

你可能感兴趣的:(mybtis-mysql模糊查询)