标签: mybatisjava
[TOC]git
本文主要讲解mybatis的输入映射。github
经过parameterType指定输入参数的类型,类型能够是sql
package com.iot.mybatis.po; /** * Created by Brian on 2016/2/24. */ public class UserQueryVo { //在这里包装所须要的查询条件 //用户查询条件 private UserCustom userCustom; public UserCustom getUserCustom() { return userCustom; } public void setUserCustom(UserCustom userCustom) { this.userCustom = userCustom; } //能够包装其它的查询条件,订单、商品 //.... }
其中,UserCustom类继承Userapache
public class UserCustom extends User{ }
在UserMapper.xml中定义用户信息综合查询(查询条件复杂,经过高级查询进行复杂关联查询)。mybatis
<!-- 用户信息综合查询 #{userCustom.sex}:取出pojo包装对象中性别值 ${userCustom.username}:取出pojo包装对象中用户名称 --> <select id="findUserList" parameterType="com.iot.mybatis.po.UserQueryVo" resultType="com.iot.mybatis.po.UserCustom"> SELECT * FROM user WHERE user.sex=#{userCustom.sex} AND user.username LIKE '%${userCustom.username}%' </select>
注意不要将#{userCustom.sex}
中的userCustom
写成UserCustom
,前者指属性名(因为使用IDE提示自动补全,因此只是把类型名首字母小写了),后者指类型名,这里是UserQueryVo
类中的userCustom
属性,是属性名。写错会报以下异常:app
org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'UserCustom' in 'class com.iot.mybatis.po.UserQueryVo' ### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'UserCustom' in 'class com.iot.mybatis.po.UserQueryVo'
//用户信息综合查询 public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;
//用户信息的综合 查询 @Test public void testFindUserList() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); //建立UserMapper对象,mybatis自动生成mapper代理对象 UserMapper userMapper sqlSession.getMapper(UserMapper.class); //建立包装对象,设置查询条件 UserQueryVo userQueryVo = new UserQueryVo(); UserCustom userCustom = new UserCustom(); //因为这里使用动态sql,若是不设置某个值,条件不会拼接在sql中 userCustom.setSex("1"); userCustom.setUsername("张三"); userQueryVo.setUserCustom(userCustom); //调用userMapper的方法 List<UserCustom> list = userMapper.findUserList(userQueryVo); System.out.println(list); }