1. 程式人生 > >mybatis學習的終極寶典

mybatis學習的終極寶典

**********************************************************************************************
一:mybatis概念
1:簡介
MyBatis本是apache的一個開源專案iBatis,2010年改名為 MyBatis,
MyBatis 是一個基於Java的持久層框架。(操作資料庫)
2:優點
1:半自動化的ORM實現(實體類和SQL語句之間建立對映關係)
2:SQL程式碼從程式程式碼中徹底分離,可重用
3:與JDBC相比,減少了50%以上的程式碼量
4:小巧靈活、簡單易學,是最簡單的持久化框架
5:提供XML標籤,支援編寫動態SQL
6:提供對映標籤,支援物件與資料庫的ORM欄位對映
3:MyBatis缺點
1:SQL語句編寫工作量大,對開發人員有一定sql技術要求
2:資料庫移植性差(不同資料庫,sql語句語法有所不同)
*******************************************mybatis環境搭建開始******************************************

1:匯入mybatis的jar包
mybatis-3.2.2.jar
mysql-connector-java-5.1.25-bin.jar

2:建立mybatis的核心配置檔案(mybatis-config.xml)
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" /> 驅動
<property name="url" value="jdbc:mysql://localhost:3306/y2t189?useUnicode=true&amp;characterEncoding=utf-8" /> 資料庫的url
<property name="username" value="root" /> 使用者名稱
<property name="password" value="zhangjiugui" /> 密碼
</dataSource>
</environment>
</environments>
<!--
dao層的mapper對映檔案(xml)
-->
<mappers>
<mapper resource="com/accp/y2t189/dao/UserMapper.xml" />
</mappers>
</configuration>

3: 實體類

4:資料訪問的介面(dao)

public List<User> findUsers();

5:介面與sql語句的對映 UserMapper.xml

名稱空間必須是響應介面的全路徑
<mapper namespace="com.accp.y2t189.dao.UserMapper">

id必須和介面中的方法名一致
resultType返回值型別(返回集合的話,指定集合元素的型別)
<select id="findUsers" resultType="com.accp.y2t189.entity.User">
SELECT * FROM users
</select>

</mapper>

6:mybatis的工具類

獲得SqlSession
①:讀取配置檔案,建立session工廠
②:在session工廠裡,獲得session會話
關閉session
判斷session例項是否建立,不為null,就關閉session

/**
* mybatis的工具類
* 獲得session
*/
public class MybatisUtil {

public static SqlSessionFactory sf; //session工廠

//獲得session工廠
static {
try {
Reader is= Resources.getResourceAsReader("mybatis-config.xml");
sf= new SqlSessionFactoryBuilder().build(is);
} catch (Exception e) {
e.printStackTrace();
}
}

//獲得session
public static SqlSession getSession(){
return sf.openSession();
}

//關閉session
public static void closeSession(SqlSession session){
if(session !=null){
session.close();
}
}
}


7: 資料操作
//獲得session
session=MybatisUtil.getSession();
//獲得介面例項
List<User> listUser=session.getMapper(UserMapper.class).findUsers();
//關閉session

*******************************************mybatis環境搭建結束******************************************
*******************************************增刪改開始***************************************************

/**
* 查詢所有資料
* @return
*/
public List<User> findAll();
******************
<select id="findAll" resultType="entity.User">
SELECT * FROM users
</select>

**************************************************

/**
* 根據編號查詢物件
* @param 使用者表的主鍵
* @return 一個物件user
*/
public User findById(Integer userId);
******************
<select id="findById" parameterType="Integer" resultType="entity.User">
select * from users where id=#{userId}
</select>

**************************************************

/**
* 增加使用者資訊
* @param 一個物件資料
* @return 資料庫的影響行數
*/
public Integer add(User user);
******************
<insert id="add" parameterType="entity.User">
INSERT INTO users VALUES(NULL,#{userName},#{password},#{realName})
</insert>

**************************************************

/**
* 根據編號刪除物件
* @param 使用者表的主鍵
* @return 資料庫的影響行數
*/
public Integer delete(Integer id);
******************
<delete id="delete" parameterType="Integer">
delete from users where id=#{id}
</delete>

**************************************************

/**
* 修改使用者資訊
* @param 一個物件資料
* @return 資料庫的影響行數
*/
public Integer update(User user);
******************
<!-- 根據屬性的主鍵修改其他的屬性值-->
<update id="update" parameterType="entity.User">
update users set userName=#{userName} ,password=#{password},realName=#{realName}
where id=#{id}
</update>

**************************************************

/**
* 連表查詢使用者資訊
* 在從表的實體類中新增級聯查詢主表中的屬性
* SELECT u.*,rolename 在使用者表中新增角色表的屬性-角色名稱
*/
public List<User> findUserAndRole();
******************
<select id="findUserAndRole" resultType="entity.User">
SELECT u.*,rolename FROM users u INNER JOIN role r
ON u.`roleid`=r.`roleid`
</select>
**************************************************

模糊查詢

//根據角色名稱,模糊查詢角色列表
public List<Role> findRoleByRoleName(String rolename);

<!--
<select id="findRoleByRoleName" resultMap="roleMapping">
SELECT * FROM role
where roleName like concat('%',#{rolename},'%')
</select>
-->
<select id="findRoleByRoleName" resultMap="roleMapping">
SELECT * FROM role
where roleName like "%"#{rolename}"%"
</select>
*******************************************增刪改查結束***************************************************
*******************************************分頁查詢開始***************************************************
/**
* 多參傳入的方法:
* 1:多個不同型別的引數入參時,對映檔案中可以不指定引數型別,
* 介面中的方法使用註解,將註解指定的名字,傳入對映檔案相應屬性中
* 2:也可以把多個引數封裝成物件,以物件型別入參
* 分頁查詢
* @param from 從第幾條開始查...
* @param pagesize 每頁顯示的記錄數
* @return 當前頁物件的集合
*/
public List<User> fenye(@Param("from")Integer from,@Param("pagesize")Integer pagesize);
******************
<select id="fenye" resultType="entity.User">
SELECT * FROM users u
INNER JOIN role r ON u.`roleid`=r.`roleid`
LIMIT #{from} ,#{pagesize}
</select>
*****************************
/**
* 查詢總記錄數
*/
public Integer count();
******************
<select id="count" resultType="Integer">
SELECT count(*) FROM users
</select>

*****************************
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");

SqlSession session=MybatisUtil.getSession(); //獲得mybatis的session物件
try {
Integer pagesize=3; //每頁顯示的記錄數
Integer page=null; //當前頁
String pageQian=req.getParameter("page");
if(pageQian !=null){
page=Integer.parseInt(pageQian);
}else{
page=1; //預設看第一頁
}
/*
* 資料庫查詢總頁數
*/
Integer count=session.getMapper(UserMapper.class).count();
int totalyeshu=0; //總頁數
if(count%pagesize==0){
totalyeshu=count/pagesize;
}else{
totalyeshu=(count/pagesize)+1;
}
/*
* 資料庫查詢當前頁的資料
*/
List<User> userList=session.getMapper(UserMapper.class).fenye((page-1)*pagesize, pagesize);
/*
* 將數傳給前臺
*/
req.setAttribute("USERLIST", userList); //集合資料
req.setAttribute("PAGE", page); //當前頁
req.setAttribute("COUNT", totalyeshu); //總頁數
} catch (Exception e) {
e.printStackTrace();
}finally{
MybatisUtil.closeSession(session);
}
req.getRequestDispatcher("indexFenye.jsp").forward(req, res); //轉發至主頁
}
*****************************
<div>
<h3 algin="right">
&lt;
<span style="font-size:12px;">共${COUNT }頁 &nbsp;/&nbsp;第${PAGE}頁 &nbsp;</span>
<c:if test="${PAGE>1 }">
<a href="fenye?page=1">首頁</a>&nbsp;
<a href="fenye?page=${PAGE-1}">上頁</a>&nbsp;
</c:if>
<c:forEach begin="1" end="${COUNT }" var="i">
<a href="fenye?page=${i}" >${i}</a>
</c:forEach>
<c:if test="${PAGE<COUNT }">
<a href="fenye?page=${PAGE+1}">下頁</a>&nbsp;
<a href="fenye?page=${COUNT}">尾頁</a>&nbsp;
</c:if>

<span style="font-size:12px;">GO</span>&nbsp;
<select id="goTo" onchange="goPage(this.value)" >
<c:forEach begin="1" end="${COUNT }" var="i" >
<option value="${i }" ${i==PAGE?"selected='selected'":"" } >${i }</option>
</c:forEach>
</select>
&nbsp;<span style="font-size:12px;">頁</span>
&gt;
</h3>
<script>
function goPage(page){
window.location.href="fenye?page="+page;
}
</script>
</div>

*******************************************分頁查詢結束***************************************************

*******************************************配置檔案開始***************************************************
列印測試的日誌資訊

1:匯入jar包 log4j-1.2.17.jar

2:在src下編寫配置檔案
log4j.properties

3:log4j.properties內容如下:

## debug 級別
log4j.rootLogger=DEBUG,Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d{yyyy-MM-dd-HH\:mm\:ss,SSS} [%t] [%c] [%p] - %m%n
log4j.logger.com.mybatis=DEBUG

##輸出sql 語句
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG</strong>

4:配置
mybatis-config.xml

<configuration>

<settings>
<setting name="logImpl" value="LOG4J" />
</settings>

<environments default="development">
</environments>
</configuration>

**************************************************
別名的建立

<settings>
</settings>

<!--類型別名 :可以在Mapper.xml對映中使用別名代替全路徑名-->
<typeAliases>
<!--type:型別的全路徑 alias:替代型別的別名 -->
<typeAlias alias="User" type="cn.zx.pojo.User"/>
<!--自動掃描此包下的所有javabean,自動生成一個預設別名,就是類名 -->
<!--<package name="cn.smbms.pojo"/>-->
</typeAliases>

<environments default="development">
</environments>


**************************************************
資料庫的資料來源引數與核心配置檔案分離

1:建立src下database.properties檔案

2:在database.properties下面寫:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/y2t189?useUnicode=true&amp;characterEncoding=utf-8
user=root
password=zhangjiugui

3:在 mybatis-config.xml下面配置

<configuration>

<!-- 引入 database.properties 檔案-->
<properties resource="database.properties"/>

<settings>
</settings>

4:將 mybatis-config.xml檔案中的引數,改為 ${database.properties配置檔案中相應的key}
<property name="driver" value="${driver}"/>

**************************************************
類中的欄位與資料庫中的屬性命名不匹配

一:類中的欄位與資料庫中的屬性命名必須一致,那麼框架才會自動為我們做資料庫中sql語句查詢出的列與類中的屬性對映

二:類中的欄位與資料庫中的屬性命名不匹配

<!--resultMap解決對映問題 type:對映型別 id:唯一標識 -->
<resultMap type="entity.Role" id="roleMapping">
<!--主鍵用id標籤 property:實體類中的id屬性 column:資料庫中id屬性對應的主鍵列-->
<id property="id" column="roleid"></id>
<!--非主鍵列 property:實體類中的相應屬性 column:資料庫中相應屬性對應的資料庫的列-->
<result property="name" column="roleName"/>
</resultMap>

<!--映入自定義的對映,使用resultMap屬性 -->
<select id="findRole" resultMap="roleMapping">
SELECT * FROM role
</select>

*******************************************配置檔案結束***************************************************

*******************************************動態查詢開始***************************************************
if動態查詢
/**
* 一:動態查詢
*/
public List<User> findUsers(@Param("userName")String userName,@Param("roleName")String roleName);
******************
<select id="findUsers" resultType="entity.User">
SELECT u.*,rolename FROM users u INNER JOIN role r
ON u.`roleid`=r.`roleid` where 1=1
<if test="userName !='' and userName !=null">
and userName=#{userName}
</if>
<if test="roleName !='' and roleName !=null">
and roleName=#{roleName}
</if>
</select>

**************************************************
if+where組合配置

public List<User> find(User user);

<!--
if+where:在包含語句前新增一個where 並 智慧判斷where、and、or關鍵字是否新增,
無需考慮因此產生的語法錯誤
-->
<select id="find" parameterType="entity.User" resultType="entity.User">
SELECT * FROM smbms_user u,smbms_role r
<where>
<if test="address!='' and address!=null">and address like CONCAT('%',#{address},'%')</if>
<if test="roleName!='' and roleName!=null">and roleName like CONCAT('%',#{roleName},'%')</if>
</where>
order by userRole desc
</select>

**************************************************
<!--
foreach (在實現 mybatis in 語句查詢時特別有用)
你可以傳遞一個List例項或者陣列作為引數物件傳給MyBatis
配置檔案中的parameterType是可以不配置的
引數:
1:collection:傳進來的引數型別
List集合寫成:”list”
陣列寫成:”array”,
其他複雜型別寫成:包含結果集List集合,在整個map集合中的鍵
2:item:臨時變數(每一個迭代元素的別名)
3:open:該語句以什麼開始
4:close:該語句以什麼結束
5:separator:多個迭代元素以什麼分隔(符)
-->

sql語句in關鍵字的用法

//根據部門條件,獲取使用者表資料列表-foreach_list
public List<User> getUserByDepId_foreach_list(List<String> roleIdList);

<!-- foreach(迴圈List<String>引數) - 作為where中in的條件 -->
<select id="getUserByDepId_foreach_list" resultType="cn.zx.pojo.User">
select * from smbms_user where userRole in
<foreach collection="list" item="roleIds" open="(" separator="," close=")">
#{roleIds}
</foreach>
</select>


測試類
List<String> list=new ArrayList<String>();
list.add("教員");
list.add("經理");

*******************************************動態查詢結束***************************************************
*******************************************配置一對多雙向對映開始*****************************************

CREATE TABLE `smbms_role` (
`id` int(10) NOT NULL PRIMARY KEY COMMENT '主鍵ID',
`roleName` varchar(15) NOT NULL COMMENT '角色名稱'
) COMMENT= '角色表'

CREATE TABLE `smbms_user` (
`id` bigint(20) PRIMARY KEY NOT NULL COMMENT '主鍵ID',
`userName` varchar(15) NOT NULL COMMENT '使用者名稱稱',
`userPassword` varchar(15) NOT NULL COMMENT '使用者密碼',
`address` varchar(30) NULL COMMENT '地址',
`userRole` int(10) NULL COMMENT '角色id'
) COMMENT= '使用者表'

**************************************************
複雜對映的環境的使用場合:
1:在得到所有使用者資訊的同時又要得到每位使用者的角色資訊(一對一,在多方新增一個一方的實體屬性)association
在得到所有角色資訊的同時又要得到每個角色下的所有使用者資訊列表(一對多,在一方新增一個多方的集合屬性)collection

使用者:多方 角色:一方

resultMap的複雜應用
1:resultMap屬性
①id:resultMap的唯一標識
②type:(對映結果的型別)Java實體類

2:resultMap子元素
①id:對映對應主鍵id,設定此項可提高MyBatis效能

②result:對映非主鍵id
property屬性:對映資料庫列的實體物件的屬性
column屬性:資料庫列名或者別名

③association: 對映到JavaBean的某個“複雜型別”屬性,比如JavaBean類
複雜的型別關聯,一對一內部巢狀 對映一個巢狀JavaBean屬性
A: association屬性:
property屬性:對映資料庫列的實體物件的屬性名
javaType屬性:完整Java類名或者別名
resultMap屬性:引用外部resultMap
B: association子元素
id:對映association屬性的javaType類的主鍵
result:對映association屬性的javaType類的簡單屬性
property屬性:對映資料庫列的實體物件的屬性
column屬性:資料庫列名或者別名

④collection: 對映到JavaBean的某個“複雜型別”屬性,比如集合
複雜型別集合,一對多,內部巢狀,對映一個巢狀結果集到一個列表
A:collection:屬性
property:對映資料庫列的實體物件的屬性
ofType:完整Java類名或者別名(集合所包括的型別)
resultMap:引用外部resultMap

注意:如果對映中出現不同欄位,的名字一樣,需要指定別名區分。
**************************************************
/**
* 根據使用者編號獲取此使用者下的使用者資訊,及每個使用者的角色資訊(association)
*/
public List<User> findRoleByUserId(Integer id);

<!—
根據使用者編號獲取此使用者下的使用者資訊,及每個使用者的角色資訊
1:在使用者表中新增 private Role role; 屬性 及 getset方法
2:<resultMap>:必須將要查的欄位,全部對映,不然查不到資料...
(除非將mybatis全域性配置檔案中設定自動對映級別為FULL)
3:association:對映單個屬性(多對一的關係)
4:如果對映中出現不同欄位,的名字一樣,需要指定別名區分。(以下標紅字型部分)
-->
<resultMap type="entity.User" id="userInRole">
<id property="id" column="id"/>
<result property="userName" column="userName"/>
<result property="userPassword" column="userPassword"/>
<result property="address" column="address"/>
<result property="userRole" column="userRole"/>
<association property="role" javaType="entity.Role">
<id property="id" column="r_id"/>
<result property="roleName" column="roleName"/>
</association>
</resultMap>
<select id="findRoleByUserId" parameterType="Integer" resultMap="userInRole">
SELECT u.*,r.`id` AS r_id ,r.roleName FROM smbms_user u , smbms_role r
WHERE u.`userRole`=r.id AND u.`id`=#{id}
</select>

public void findRoleByUserId(){
session=MybatisUtil.getSqlSession();
List<User> list=session.getMapper(InfoMapper.class).findRoleByUserId(1);
for(User user :list){
System.out.println(user.getId()+"\t"+user.getUserName());
System.out.println("\t\t"+user.getRole().getId()+"\t"
+user.getRole().getRoleName());
}
}
**************************************************
/**
* 獲取指定角色編號下的使用者列表(collection)
*/
public List<Role> findUserByRoleId(Integer id);

<!—
獲取指定角色編號下的使用者列表
在角色表中新增屬性:private List<User> userList; 及getset方法
獲取指定角色的使用者列表(collection) 對映一對多關係的關係
-->
<resultMap type="entity.Role" id="roleInUser">
<id property="id" column="r_id"/>
<result property="roleName" column="roleName"/>
<collection property="userList" ofType="entity.User" resultMap="userInRole" />
</resultMap>
<select id="findUserByRoleId" parameterType="Integer" resultMap="roleInUser">
SELECT u.*,r.`id` AS r_id ,r.roleName FROM smbms_user u , smbms_role r
WHERE u.`userRole`=r.id AND r.id=#{id}
</select>

public void findUserByRoleId(){
session=MybatisUtil.getSqlSession();
List<Role> list=session.getMapper(InfoMapper.class).findUserByRoleId(1);
for(Role role :list){
System.out.println(role.getId()+"\t"+role.getRoleName());
for(User user :role.getUserList()){
System.out.println("\t\t"+user.getUserName()+"\t"+user.getUserPassword());
}
}
}
**************************************************
<!—
基於映射覆用的寫法

<resultMap type="entity.User" id=" userInRole ">
<id property="id" column="id"/>
<result property="userName" column="userName"/>
<result property="userPassword" column="userPassword"/>
<result property="address" column="address"/>
<association property="role" javaType="cn.zx.pojo.Role" resultMap="roleResult"/>
</resultMap>

<resultMap type="cn.zx.pojo.Role" id="roleResult">
<id property="id" column="r_id"/>
<result property="roleName" column="roleName"/>
</resultMap>
-->
*******************************************配置一對多雙向對映結束***********************************
*******************************************配置檔案補充開始*****************************************
<configuration>
<settings>
<!--
實體類的屬性,與資料庫中的列,對映設定
設定resultMap的自動對映級別為:
NONE :禁止自動匹配 <resultMap>中必須將所有需要的實體類的屬性,與資料庫中的列,全部對映上
PARTIAL(預設) 自動匹配所有屬性(含有association,collection的<resultMap>除外)
FULL :自動匹配所有
-->
<setting name="autoMappingBehavior" value="PARTIAL" />
</settings>

</configuration>

**************************************************
public static SqlSession createSqlSession(){
//true 關閉事務控制 預設為true 在增刪改的時候有一定危險(無需手動提交或回滾事務)
//false 開啟事務控制 提交sqlSession.commit(); 回滾sqlSession.rollback();
return factory.openSession(false);
}
*******************************************配置檔案補充結束*****************************************
*******************************************動態查詢拓展*********************************************
<!--
choose (when:分支條件 ,otherwize:以上條件都不滿足執行此)
注意:此種查詢結果為:只滿足一種條件就執行查詢
-->
<select id="getUserList_choose" resultType="User">
select * from smbms_user where 1=1
<choose>
<when test="userName != null and userName != ''">
and userName = #{userName}
</when>
<when test="userRole != null">
and userRole= #{userRole}
</when>
<otherwise>
and id=#{id}
</otherwise>
</choose>
</select>
*******************************************

//修改
public int updateUser(User user);

<!--
if/set(判斷引數) 用於更新操作,在包含語句前新增一個set 並
他將自動智慧判斷每個if條件後是否新增",")
-->
<update id="updateUser" parameterType="entity.User">
update smbms_user
<set>
<if test="userName!='' and userName!=null">userName=#{userName},</if>
<if test="address!='' and address!=null">address =#{address},</if>
<if test="roleName!='' and roleName!=null">roleName =#{roleName},</if>
<if test="userPassword!='' and userPassword!=null">
userPassword =#{userPassword},
</if>
<if test="userRole!='' and userRole!=null">userRole =#{userRole},</if>
</set>
where id=#{id}
</update>

<!—
對整個trim包含的內容智慧自動判斷是否加上 prefix字首,或者 suffix字尾
prefixOverrides:自動判斷子語句if前面的條件語句是否新增或不新增其值
suffixOverrides:自動判斷子語句if後邊的條件語句是否新增或不新增其值
-->
<update id="updateUser" parameterType="entity.User">
update smbms_user
<trim prefix="set" suffixOverrides="," suffix="where id=#{id}">
<if test="userName!='' and userName!=null">userName=#{userName},</if>
<if test="address!='' and address!=null">address =#{address},</if>
<if test="roleName!='' and roleName!=null">roleName =#{roleName},</if>
<if test="userPassword!='' and userPassword!=null">
userPassword =#{userPassword},
</if>
<if test="userRole!='' and userRole!=null">userRole =#{userRole},</if>
</trim>
</update>
*******************************************

<!--
foreach (在實現 mybatis in 語句查詢時特別有用)
你可以傳遞一個List例項或者陣列作為引數物件傳給MyBatis
配置檔案中的parameterType是可以不配置的
引數:
1:collection:傳進來的引數型別
List集合寫成:”list”
陣列寫成:”array”,
其他複雜型別寫成:包含結果集List集合,在整個map集合中的鍵
2:item:臨時變數(每一個迭代元素的別名)
3:open:該語句以什麼開始
4:close:該語句以什麼結束
5:separator:多個迭代元素以什麼分隔(符)
-->
//根據部門條件,獲取使用者表資料列表-foreach_array
public List<User> getUserByDepId_foreach_array(String[] arrys);

<!-- foreach(迴圈array引數) - 作為where中in的條件 -->
<select id="getUserByDepId_foreach_array" resultType="cn.zx.pojo.User">
select * from smbms_user where userRole in
<foreach collection="array" item="roleId" open="(" separator="," close=")">
#{roleId}
</foreach>
</select>

String[] depIds = {"1","2"};
sqlSession = MyBatisUtil.createSqlSession();
List<User> userList = new ArrayList<User>();
userList = sqlSession.getMapper(SqlQrendMap.class).getUserByDepId_foreach_array(depIds);

***************************
//根據部門條件,獲取使用者表資料列表-foreach_list
public List<User> getUserByDepId_foreach_list(List<String> roleIdList);

<!-- foreach(迴圈List<String>引數) - 作為where中in的條件 -->
<select id="getUserByDepId_foreach_list" resultType="cn.zx.pojo.User">
select * from smbms_user where userRole in
<foreach collection="list" item="roleIds" open="(" separator="," close=")">
#{roleIds}
</foreach>
</select>

List<String> depIdList = new ArrayList<String>();
depIdList.add("1");
depIdList.add("2");
depIdList.add("4");
sqlSession = MyBatisUtil.createSqlSession();
List<User> userList = new ArrayList<User>();
userList = sqlSession.getMapper(SqlQrendMap.class).getUserByDepId_foreach_list(depIdList);
***************************
//根據使用者角色列表和性別(多引數),獲取該角色列表下並指定性別的使用者列表資訊-foreach_map -->
public List<User> getUserByConditionMap_foreach_map(Map<String,Object> map);
<select id="getUserByConditionMap_foreach_map" resultType="cn.zx.pojo.User">
select * from smbms_user where userName = #{userName} and userRole in
<foreach collection="roleIds" item="roleMap" open="(" separator="," close=")">
#{roleMap}
</foreach>
</select>
List<Integer> roleList = new ArrayList<Integer>();
roleList.add(1);
roleList.add(3);
Map<String, Object> conditionMap = new HashMap<String,Object>();
conditionMap.put("userName", "admin");
conditionMap.put("roleIds",roleList);
List<User> userList = new ArrayList<User>();
userList = sqlSession.getMapper(SqlQrendMap.class).getUserByConditionMap_foreach_map(conditionMap);

*******************************************動態查詢拓展*****************************************