关于Mybatis中的条件查询。createCriteria example里面的条件

2022-06-27 11:05:55

        之前用Mybatis框架反向的实体,还有实体里面的Example,之前只是知道Example里面放的是条件查询的方法,可是一直不知道怎么用,到今天才开始知道怎么简单的用。

        在我们前台查询的时候会有许多的条件传过来:先看个例子:

public List<Contact> searchByExample(Contact contact) {  
        System.out.println("searchByExampleContact");  
        ContactExample example = new ContactExample();  
        ContactExample.Criteria cri = example.createCriteria();  
        // //  
        if (this.objectAttrNullCheck(contact, "username"))  
            cri.andUsernameEqualTo(contact.getUsername());  
        if (this.objectAttrNullCheck(contact, "password"))  
            cri.andPasswordEqualTo(contact.getPassword());  
   
        ContactMapper vcontactMapper = sqlSession  
                .getMapper(ContactMapper.class);  
        List<Contact> returnList = vcontactMapper.selectByExample(example);  
        return returnList;  
    }

这是简单的用户登录的后台代码,example中有一个Criterria的方法,里面

andUsernameEqualTo
andPasswordEqualTo

都是在生成example的时候生成的。这两个方法是判断单值的。

简单介绍下,都是百度的:

  • Criteria

Criteria包含一个Cretiron的集合,每一个Criteria对象内包含的Cretiron之间是由AND连接的,是逻辑与的关系。

oredCriteria

Example内有一个成员叫oredCriteria,是Criteria的集合,就想其名字所预示的一样,这个集合中的Criteria是由OR连接的,是逻辑或关系。oredCriteria就是ORed Criteria。

其他

Example类的distinct字段用于指定DISTINCT查询。

orderByClause字段用于指定ORDER BY条件,这个条件没有构造方法,直接通过传递字符串值指定。

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
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;
import org.apache.log4j.pattern.ClassNamePatternConverter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import cn.itcast.ssm.mapper.ItemsMapper;
import cn.itcast.ssm.po.ItemsExample;
 
public class Student {
 
    public static void main(String[] args) throws IOException {
 
        /*方式一  */
        ItemsExample itemsExample1 = new ItemsExample();
 
        itemsExample1.or().andIdEqualTo(5).andNameIsNotNull();
        itemsExample1.or().andPicEqualTo("xxx").andPicIsNull();
 
        List<Integer> fieldValues = new ArrayList<Integer>();
        fieldValues.add(8);
        fieldValues.add(11);
        fieldValues.add(14);
        fieldValues.add(22);
        itemsExample1.or().andIdIn(fieldValues);
        itemsExample1.or().andIdBetween(5, 9);
 
        /*  方式二 criteria1与criteria2是or的关系 */
 
        ItemsExample itemsExample2 = new ItemsExample();
        ItemsExample.Criteria criteria1 = itemsExample2.createCriteria();
        criteria1.andIdIsNull();
        criteria1.andPriceEqualTo((float) 3);
 
        ItemsExample.Criteria criteria2 = itemsExample2.createCriteria();
        criteria2.andNameIsNull();
        criteria2.andIdGreaterThanOrEqualTo(5);
        itemsExample2.or(criteria2);
 
        //方式一和方式二是等价的
         
         
        // spring获取mapper代理对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        ItemsMapper itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
        itemsMapper.countByExample(itemsExample2);
 
        // 获取SqlSessionFactory
        String resource = "SqlMapConfig.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
        // 获取SqlSession
        SqlSession sqlSession = sqlMapper.openSession();
 
    }
}


avaBeans类的成员变量一般称为属性(property)。对每个属性访问权限一般定义为private或protected,而不是定义为public的。注意:属性名必须以小写字母开头。

对每个属性,一般定义两个public方法,它们分别称为访问方法(getter)和修改方法(setter),允许容器访问和修改bean的属性。

      public String getColor();

      public void setColor(String);

一个例外是当属性是boolean类型时,访问器方法应该定义为isXxx()形式。

对象类型

虽然可以明确的引用对象的属性名了,但如果要在if元素中测试传入的user参数,仍然要使用_parameter来引用传递进来的实际参数,因为传递进来的User对象的名字是不可考的。如果测试对象的属性,则直接引用属性名字就可以了。

测试user对象:

<if test="_parameter != null">

传入对象属性

<if test="name != null">

map类型

传入map类型,直接通过#{keyname}就可以引用到键对应的值。使用@param注释的多个参数值也会组装成一个map数据结构,和直接传递map进来没有区别。

mapper接口:

int updateByExample(@Param("user") User user, @Param("example") UserExample example);

sql映射:

<update id="updateByExample" parameterType="map" >
    update tb_user
    set id = #{user.id,jdbcType=INTEGER},
    ...
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>

注意这里测试传递进来的map是否为空,仍然使用_parameter

以上参考:http://blog.51cto.com/tianxingzhe/1741268

        再来看看我的项目中的,我写的是项目的接口开发,前端要穿写条件进来查询,前端的传参格式:

传参格式:
	 * {    
     	"currPage": 0,
    	"startRow": 0,
    	"pageSize": 20,
    	"map":{
    		"andStealtollTypeEqualTo":1		
    	}
     }

注意map里面的传的参数格式:全部是example里面的参数格式,如果还要传入什么参数直接在里面加(相当于前端传过来的条件),这些条件全部放进map里面,

HisVehReviewHandleExample example = new HisVehReviewHandleExample();
		example.setPage(page);//将前面传过来的page数据放进example中
		popQeuryExample(example.getPage().getMap(), example.createCriteria());
		vehReviewService.queryPage(example);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("page", page);
		//map.put("typeCount", value);
		result.setData(map);
		writeJson(response, JSON.toJSON(result));


service层:

public Page<HisVehReviewHandle> queryPage(HisVehReviewHandleExample example) {
		Page<HisVehReviewHandle> page = example.getPage();
		List<HisVehReviewHandle> list = HisVehReviewHandleMapper.selectByExample(example);
		System.out.println("查询list成功"+list.get(0).getStealtollType()+" "+list.get(0).getStealtollTypeName());
		int count = HisVehReviewHandleMapper.countByExample(example);
		page.setRows(list);
		page.setTotalCount(count);
		return page;
	}


sql语句查询exaple的:

<select id="selectByExample" parameterType="com.vrview.ssm.model.example.HisVehReviewHandleExample" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Wed Jan 17 10:03:58 CST 2018.
    -->
    <include refid="OracleDialectPrefix" />
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from HIS_VEH_REVIEW_HANDLE
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
    <include refid="OracleDialectSuffix" />
  </select>

sql语句,用来查询数量的:

<select id="countByExample" parameterType="com.vrview.ssm.model.example.HisVehReviewHandleExample" resultType="java.lang.Integer">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Wed Jan 17 10:03:58 CST 2018.
    -->
    select count(*) from HIS_VEH_REVIEW_HANDLE
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>

关于参数_paramerter:参考:http://blog.csdn.net/u014476019/article/details/45878771

这部分就是对criteria里面的参数进行判断,进而根据条件查询。

<sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">//没有值
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">//单个值
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">//区间值,范围查询
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">//一组值
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  • 作者:静风落叶
  • 原文链接:https://blog.csdn.net/qq_34178998/article/details/79103586
    更新时间:2022-06-27 11:05:55