標籤: 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); }