[轉(zhuǎn)載]MyBatis基本查詢,mapper文件的定義

原文鏈接:http://blog.csdn.net/tototuzuo ... 01099


1 PersonTestMapper.xml中的內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis ... gt%3B
<!--
  namespace:命名空間,用來唯一標識一個映射文件,命名規(guī)范就是當前的文件的包加上文件名
 -->
<mapper namespace="com.rl.mapper.PersonTestMapper">
    <!--
       根據(jù)id來查詢一個Person的數(shù)據(jù)
       sql語句接收參數(shù)的一個語法#{}镀琉,如果接收的是一個{}中的內(nèi)容任意select * from person_test t where t.ID = ?,使用預(yù)編譯方式生成sql
       id:sql語句的唯一的標識不能重復(fù)
       parameterType:sql要接收的數(shù)據(jù)類型
       resultType:sql所返回的數(shù)據(jù)類型
     -->
     
     <!--
        實際項目中數(shù)據(jù)庫的表的字段一般由多個單詞來構(gòu)成 由下劃線來分隔多個單詞 person_addr
        在java的model的實體類中的屬性多個單詞的命名規(guī)范是駝峰模式personAddr
      -->
     <select id="selectPersonById" parameterType="java.lang.Integer" resultType="com.rl.model.Person">
        select * from person_test t where t.ID = #{id}
     </select>
</mapper>
2  PersonMapper.xml的配置內(nèi)容如下(resultMap配置返回值恶导,sql片段配置,select標簽標簽中的內(nèi)容介紹鬼贱,配置使用二級緩存,使用別名的數(shù)據(jù)類型香璃,條件查詢map傳遞參數(shù)这难,模糊查詢,插入葡秒,更新姻乓,刪除,where條件查詢眯牧,動態(tài)修改蹋岩,in查詢foreach迭代,批量插入foreach,批量刪除学少,一對多查詢剪个,extends:resultMap的繼承,多對多查詢版确,延遲加載):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis ... gt%3B
<!--
namespace:命名空間扣囊,用來唯一標識一個映射文件,命名規(guī)范就是當前的文件的包名+mapper的xml文件名
 -->
<mapper namespace="com.rl.mapper.PersonMapper">
    <!--當前映射文件開啟二級緩存-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
    <!--
        id:resultMap的唯一標識
        type:給哪個實體類做結(jié)果的映射
    -->
    <resultMap type="person" id="BaseResultMap">
        <!--
            column:數(shù)據(jù)庫中表的字段
            property:數(shù)據(jù)庫中表所有映射的實體類javaBean中的屬性名
         -->
        <id column="person_id" property="personId"/>
        <result column="name" property="name"/>
        <result column="gender" property="gender"/>
        <result column="person_addr" property="personAddr"/>
        <result column="birthday" property="birthday"/>
    </resultMap>
   
    <!--
        公用的sql片段,也可以接收參數(shù)乎折,動態(tài)sql,所有的sql可以使用
     -->
    <sql id="columns">
        PERSON_ID, NAME, GENDER, PERSON_ADDR, BIRTHDAY
    </sql>
   
    <!--
        根據(jù)id來查詢一個Person的數(shù)據(jù)
        sql語句接收參數(shù)的一個語法#{}如暖,如果接收的是一個{}中的內(nèi)容任意select * from person_test t where t.ID = ?,使用預(yù)編譯方式生成sql
        id:sql語句的唯一的標識不能重復(fù)
        parameterType:sql要接收的數(shù)據(jù)類型
        resultType:sql所返回的數(shù)據(jù)類型
     -->
     <!--
        實際項目中數(shù)據(jù)庫的表的字段一般由多個單詞來構(gòu)成 由下劃線來分隔多個單詞 person_addr
        在java的model的實體類中的屬性多個單詞的命名規(guī)范是駝峰模式personAddr
      -->
      <!--
        useCache:控制當前的這個sql是否使用二級緩存
       -->
     <select id="selectPersonById" parameterType="int" resultMap="BaseResultMap" useCache="true">
        select * from person t where t.person_id = #{id}
     </select>
     
     <select id="selectPersonCount" resultType="int">
        select count(*) from person
     </select>
     
     <!-- 這里引用了上面的sql片段 -->
     <select id="selectPersonAll" resultMap="BaseResultMap">
        select <include refid="columns"/> from person
     </select>
     
     <!--
        可以使用map
        map.put("gender",1);
        map.put("birthday" new Date());
        #{}中的內(nèi)容使用Map的key來接收參數(shù)
      -->
     <select id="selectPersonByParams" parameterType="map" resultMap="BaseResultMap">
        <![CDATA[
            select * from person t where t.gender = #{gender} and t.birthday < #{birthday}
        ]]>
     </select>
     
     <!--
        使用查詢對象的get方法來接收參數(shù)(也就是屬性名)
      -->
     <select id="selectPersonByParams1" parameterType="qc" resultMap="BaseResultMap">
        <![CDATA[
            select * from person t where t.gender = #{gender} and t.birthday < #{birthday}
        ]]>
     </select>
     <!--
        模糊查詢使用${} select * from person t where t.name like '%安%'
        parameterType:不能直接使用String,一定要用查詢對象或者map
      -->
    <select id="selectPersonByLike" parameterType="qc" resultMap="BaseResultMap">
        select * from person t where t.name like '%${name}%'
    </select>
   
    <!-- 庫表變更 -->
    <insert id="insert" parameterType="person">
        <!--
            keyProperty:實體類中主鍵屬性笆檀,主鍵生成后把主鍵返回給這個屬性
            order:生成主鍵的sql和insert執(zhí)行的順序, mysql是AFTER盒至, oracle是BEFORE
            resultType: 主鍵返回的數(shù)據(jù)類型
            sql:
                在mysql中select LAST_INSERT_ID()
                在oracle中 select xxx.nextval from dual
                   
            selectKey做了兩件事:1.主鍵自增 2.主鍵返回
         -->
        <selectKey keyProperty="personId" order="AFTER" resultType="int">
            select LAST_INSERT_ID()
        </selectKey>
        insert into person (person_id, name, gender, person_addr, birthday)
        values(#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday})
    </insert>
   
    <update id="update" parameterType="person">
        update person p set p.name = #{name},
        p.gender = #{gender},
        p.person_addr = #{personAddr},
        p.birthday = #{birthday}
        where p.person_id = #{personId}
    </update>
   
    <!--
        刪除的sql不能使用別名
     -->
    <delete id="delete" parameterType="int">
        delete from person where person_id = #{personId}
    </delete>
   
    <!-- =============================動態(tài)sql================================== -->
    <!--
        map.put("name", "安");
        map.put("gender", "0");
        map.put("personAddr", "東京")
        map.put("birthday", new Date());
       
        <where>會自動處理and酗洒, 第一個and可以不寫,其他的and必須要寫
     -->
    <select id="selectPersonByCondition" parameterType="map" resultMap="BaseResultMap">
        select * from person t
        <where>
            <if test="name != null">
                 t.name like '%${name}%'
            </if>
            <if test="gender != null">
                and t.gender = #{gender}
            </if>
            <if test="personAddr != null">
                and t.person_addr like '%${personAddr}%'
            </if>
            <if test="birthday != null">
                <![CDATA[
                    and t.birthday < #{birthday}
                ]]>
            </if>
        </where>
    </select>
   
    <!--
        動態(tài)修改
        <set>標簽可以去掉最后一個逗號
       
        flushCache:二級緩存的刷新的配置:默認是true:會刷新枷遂,如果false就不刷新緩存
     -->
    <update id="dynamicUpdate" parameterType="person" flushCache="false">
        update person t
        <set>
            <if test="name != null">
                t.name = #{name},
            </if>
            <if test="gender != null">
                t.gender = #{gender},
            </if>
            <if test="personAddr != null">
                t.person_addr = #{personAddr},
            </if>
            <if test="birthday != null">
                t.birthday = #{birthday}
            </if>
        </set>
        where t.person_id = #{personId}
    </update>
   
    <!--
        select * from person t where t.person_id in (1,2,3)
        map.put("ids", list);
     -->
    <select id="selectPersonByIn" parameterType="map" resultMap="BaseResultMap">
        select * from person t where t.person_id in
        <foreach collection="ids" item="personId" open="(" close=")" separator="," index="index">
            #{personId}
        </foreach>
    </select>
       
    <!--
    map.put("pList", pList);
   
    insert into person (person_id, name, gender, person_addr, birthday)
        values
        (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}),
        (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}),
        (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}),
        (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}),
        (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday});
     -->
    <insert id="insertBatch" parameterType="map">
        <selectKey keyProperty="personId" order="AFTER" resultType="int">
            select LAST_INSERT_ID()
        </selectKey>
        insert into person (person_id, name, gender, person_addr, birthday)
        values
        <foreach collection="pList" item="person" separator=",">
            (#{person.personId}, #{person.name}, #{person.gender}, #{person.personAddr}, #{person.birthday})
        </foreach>
    </insert>
   
    <delete id="deleteBatch" parameterType="map">
        delete from person where person_id in
        <foreach collection="ids" item="personId" open="(" close=")" separator="," index="index">
            #{personId}
        </foreach>
    </delete>
   
    <!-- ===============================關(guān)聯(lián)查詢================== -->
    <!-- 一對多 -->
    <resultMap type="person" id="selectPersonAndOrderByPIdRM">
        <id column="person_id" property="personId"/>
        <result column="name" property="name"/>
        <result column="gender" property="gender"/>
        <result column="person_addr" property="personAddr"/>
        <result column="birthday" property="birthday"/>
        <!--
        collection:一對多的關(guān)聯(lián)映射
        property:一的端集合的屬性名
        ofType:集合中的泛型
         -->
        <collection property="ordersList" ofType="com.rl.model1.Orders">
            <id column="ORDER_ID" property="orderId" jdbcType="INTEGER" />
            <result column="PERSON_ID" property="personId" jdbcType="INTEGER" />
            <result column="TOTAL_PRICE" property="totalPrice" jdbcType="REAL" />
            <result column="ADDR" property="addr" jdbcType="VARCHAR" />
        </collection>
    </resultMap>
   
    <!--
        extends:resultMap的繼承
     -->
    <resultMap type="person" id="selectPersonAndOrderByPIdRM1" extends="BaseResultMap">
        <collection property="ordersList" ofType="com.rl.model1.Orders">
            <id column="ORDER_ID" property="orderId" jdbcType="INTEGER" />
            <result column="PERSON_ID" property="personId" jdbcType="INTEGER" />
            <result column="TOTAL_PRICE" property="totalPrice" jdbcType="REAL" />
            <result column="ADDR" property="addr" jdbcType="VARCHAR" />
        </collection>
    </resultMap>
   
    <resultMap type="person" id="selectPersonOrderAndDetailByPIdRM" extends="BaseResultMap">
        <collection property="ordersList" ofType="com.rl.model1.Orders">
            <id column="ORDER_ID" property="orderId" jdbcType="INTEGER" />
            <result column="PERSON_ID" property="personId" jdbcType="INTEGER" />
            <result column="TOTAL_PRICE" property="totalPrice" jdbcType="REAL" />
            <result column="ADDR" property="addr" jdbcType="VARCHAR" />
           
            <collection property="detailList" ofType="com.rl.model1.OrderDetail">
            <id column="DETAIL_ID" property="detailId" jdbcType="INTEGER" />
                <result column="ORDER_ID" property="orderId" jdbcType="INTEGER" />
                <result column="PRICE" property="price" jdbcType="REAL" />
                <result column="QUANTITY" property="quantity" jdbcType="INTEGER" />
                <result column="ITEM_NAME" property="itemName" jdbcType="VARCHAR" />
            </collection>
        </collection>
    </resultMap>
   
    <resultMap type="person" id="selectPersonAndRoleByPIdRM" extends="BaseResultMap">
        <collection property="roleList" ofType="com.rl.model1.Role">
            <id column="ROLE_ID" property="roleId" jdbcType="INTEGER" />
            <result column="ROLE_NAME" property="roleName" jdbcType="VARCHAR" />
            <result column="DESCRIPT" property="descript" jdbcType="VARCHAR" />
        </collection>
    </resultMap>
   
    <select id="selectPersonAndOrderByPId" parameterType="int" resultMap="selectPersonAndOrderByPIdRM1">
        select * from person p, orders o where p.PERSON_ID = o.PERSON_ID and p.PERSON_ID = #{personId}
    </select>
 
    <select id="selectPersonOrderAndDetailByPId" parameterType="int" resultMap="selectPersonOrderAndDetailByPIdRM">
        select * from person p,
        orders o,
        order_detail od where
        p.PERSON_ID = o.PERSON_ID
        and o.ORDER_ID = od.ORDER_ID
        and p.PERSON_ID = #{personId}
    </select>
   
    <!-- 多對多從Person一端看 -->
    <select id="selectPersonAndRoleByPId" parameterType="int" resultMap="selectPersonAndRoleByPIdRM">
        SELECT p.*, r.* from person p,
        person_role pr,
        role r where
        p.PERSON_ID = pr.PERSON_ID
        and pr.ROLE_ID = r.ROLE_ID
        and p.PERSON_ID = #{personId}
    </select>
   
    <!-- =========================延遲加載======================== -->
    <resultMap type="person" id="selectPersonByIdLazyRM" extends="BaseResultMap">
        <!--
            column:主sql的一列作為子sql的參數(shù)
            select:指定子sql的位置
         -->
        <collection property="ordersList" column="person_id" select="com.rl.mapper.OrdersMapper.selectOrderByPersonId">
        </collection>
    </resultMap>
   
    <select id="selectPersonByIdLazy" parameterType="int" resultMap="selectPersonByIdLazyRM">
        select * from person t where t.person_id = #{personId}
    </select>
</mapper>
3 配置sqlMapConfig.xml中的<mappers>配置:
<!-- 集中管理表的映射文件 -->
<mappers>
   <mapper resource="com/rl/mapper/PersonTestMapper.xml" />
   <mapper resource="com/rl/mapper/PersonMapper.xml" />
   <mapper resource="com/rl/mapper/RoleMapper.xml" />
   <mapper resource="com/rl/mapper/OrdersMapper.xml" />
   <mapper resource="com/rl/mapper/OrderDetailMapper.xml" />
</mappers>
4 測試代碼如下:
MybatisTest.java
package com.rl.test;
 
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
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.junit.Before;
import org.junit.Test;
 
import com.rl.model1.Person;
import com.rl.model1.QueryCondition;
 
/**
 * mybatis的簡單查詢
 */
public class MybatisTest {
         SqlSessionFactory sessionFactory;
        
         @Before
         public void setUp() throws Exception {
                   InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
                   sessionFactory = new SqlSessionFactoryBuilder().build(in);
         }
 
         /**
          * 通過id查詢數(shù)據(jù)
          */
         @Test
         public void selectPersonById() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            //第一個參數(shù):指定要執(zhí)行的sql語法是namespace.sql的id樱衷,第二個參數(shù)sql要接收的參數(shù)
                            com.rl.model.Person person  = session.selectOne(
                                     "com.rl.mapper.PersonTestMapper.selectPersonById", 1);
                            System.out.println(person);
                   } finally{
                            session.close();
                   }
         }
        
         /**
          * 使用resultMap來查詢
          */
         @Test
         public void selectPersonById1() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            //第一個參數(shù):指定要執(zhí)行的sql語法是namespace.sql的id,第二個參數(shù)sql要接收的參數(shù)
                            Person person  = session.selectOne("com.rl.mapper.PersonMapper.selectPersonById", 1);
                            System.out.println(person);
                   } finally{
                            session.close();
                   }
         }
        
         /**
          * 查詢表的記錄數(shù)
          */
         @Test
         public void selectPersonCount() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            Integer count = session.selectOne("com.rl.mapper.PersonMapper.selectPersonCount");
                            System.out.println(count);
                   } finally{
                            session.close();
                   }                
         }
        
         /**
          * 查詢所有Person
          */
         @Test
         public void selectPersonAll() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            //查詢集合的時候需要使用selectList
                            List<Person> pList = session.selectList("com.rl.mapper.PersonMapper.selectPersonAll");
                            for(Person p : pList){
                                     System.out.println(p);
                            }
                   } finally{
                            session.close();
                   }
         }
        
         /**
          * 使用多個參數(shù)用Map方式來查詢
          */
         @Test
         public void selectPersonByParams() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("gender",0);
                           map.put("birthday", new Date());
                            //查詢集合的時候需要使用selectList
                            List<Person> pList = session.selectList("com.rl.mapper.PersonMapper.selectPersonByParams",map);
                            for(Person p : pList){
                                     System.out.println(p);
                            }
                   } finally{
                            session.close();
                   }
         }
        
         /**
          * 使用多個參數(shù)查詢數(shù)據(jù)酒唉,使用查詢對象的方式
          */
         @Test
         public void selectPersonByParams1() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            QueryCondition qc = new QueryCondition();
                            qc.setGender("0");
                            qc.setBirthday(new Date());
                            //查詢集合的時候需要使用selectList
                            List<Person> pList = session.selectList("com.rl.mapper.PersonMapper.selectPersonByParams1",qc);
                            for(Person p : pList){
                                     System.out.println(p);
                            }
                   } finally{
                            session.close();
                   }
         }
        
         /**
          * 模糊查詢
          */
         @Test
         public void selectPersonByLike() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            QueryCondition qc = new QueryCondition();
                            qc.setName("武");
                            //查詢集合的時候需要使用selectList
                            List<Person> pList = session.selectList("com.rl.mapper.PersonMapper.selectPersonByLike",qc);
                            for(Person p : pList){
                                     System.out.println(p);
                            }
                   } finally{
                            session.close();
                   }
         }
}
MybatisTest1.java的內(nèi)容如下:
package com.rl.test;
 
import java.io.InputStream;
import java.util.Date;
 
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.junit.Before;
import org.junit.Test;
 
import com.rl.model1.Person;
 
/**
 * mybatis的數(shù)據(jù)庫表的變更
 */
public class MybatisTest1 {
         SqlSessionFactory sessionFactory;
        
         @Before
         public void setUp() throws Exception {
                   InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
                   sessionFactory = new SqlSessionFactoryBuilder().build(in);
         }
 
         /**
          * 數(shù)據(jù)插入主鍵返回
          * public void saveOrder(Orders order, List<OrderDetail> detailList){
                            orderDao.save(order);
                            for(OrderDetail detail : detailList){
                                     detail.setOrderId(order.getOrderId());
                                     detailDao.save(detail)
                            }
                   }
          */
         @Test
         public void insert(){
                   SqlSession session = sessionFactory.openSession();
                   Person p = new Person();
                   //p.setPersonId(3);
                   p.setName("武松");
                   p.setGender("0");
                   p.setPersonAddr("陽谷縣");
                   p.setBirthday(new Date());
                   try {
                            session.insert("com.rl.mapper.PersonMapper.insert", p);
                            //庫表的變更都需要提交
                            session.commit();
                   } catch (Exception e) {
                            e.printStackTrace();
                            session.rollback();
                   }finally{
                            session.close();
                   }
         }
        
         /**
          * 修改矩桂,將id是3的記錄改成
          */
         @Test
         public void update(){
                   SqlSession session = sessionFactory.openSession();
                   Person p = new Person();
                   p.setPersonId(3);
                   p.setName("陸虞候");
                   p.setGender("0");
                   p.setPersonAddr("陽谷縣");
                   p.setBirthday(new Date());
                   try {
                            session.update("com.rl.mapper.PersonMapper.update", p);
                            //庫表的變更都需要提交
                            session.commit();
                   } catch (Exception e) {
                            e.printStackTrace();
                            session.rollback();
                   }finally{
                            session.close();
                   }
         }
        
         /**
          * 刪除
          */
         @Test
         public void delete(){
                   SqlSession session = sessionFactory.openSession();
                   try {
                            session.delete("com.rl.mapper.PersonMapper.delete", 4);
                            //庫表的變更都需要提交
                            session.commit();
                   } catch (Exception e) {
                            e.printStackTrace();
                            session.rollback();
                   }finally{
                            session.close();
                   }
         }
}
MybatisTest2.java
package com.rl.test;
 
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
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.junit.Before;
import org.junit.Test;
 
import com.rl.model1.Person;
 
 
/**
 * mybatis的動態(tài)sql
 */
public class MybatisTest2 {
 
         SqlSessionFactory sessionFactory;
        
         @Before
         public void setUp() throws Exception {
                   InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
                   sessionFactory = new SqlSessionFactoryBuilder().build(in);
         }
 
         @Test
         public void selectPersonByCondition() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("name", "安");
                            map.put("gender", "0");
                            //map.put("personAddr", "東京");
                            //map.put("birthday", new Date());
                            //第一個參數(shù):指定要執(zhí)行的sql語法是namespace.sql的id,第二個參數(shù)sql要接收的參數(shù)
                            List<Person> pList  = session.selectList("com.rl.mapper.PersonMapper.selectPersonByCondition", map);
                            for(Person p : pList){
                                     System.out.println(p);
                            }
                   } finally{
                            session.close();
                   }
                  
         }
        
         @Test
         public void dynamicUpdate(){
                   SqlSession session = sessionFactory.openSession();
                   Person p = new Person();
                   p.setPersonId(3);
                   p.setName("陸虞候");
                   p.setGender("0");
                   //p.setPersonAddr("陽谷縣");
                   //p.setBirthday(new Date());
                   try {
                            session.update("com.rl.mapper.PersonMapper.dynamicUpdate", p);
                            //庫表的變更都需要提交
                            session.commit();
                   } catch (Exception e) {
                            e.printStackTrace();
                            session.rollback();
                   }finally{
                            session.close();
                   }
         }
        
         /**
          * foreach的用法
          */
         @Test
         public void selectPersonByIn() {
                   //創(chuàng)建session對象
                   SqlSession session = sessionFactory.openSession();
                   try {
                            Map<String, Object> map = new HashMap<String, Object>();
                            /*List list = new ArrayList();
                            list.add(1);
                            list.add(2);
                            list.add(3);*/
                            String [] list = {"1","2","3"};
                            map.put("ids", list);
                            List<Person> pList  = session.selectList("com.rl.mapper.PersonMapper.selectPersonByIn", map);
                            for(Person p : pList){
                                     System.out.println(p);
                            }
                   } finally{
                            session.close();
                   }
                  
         }
        
         /**
          * 批量插入
          */
         @Test
         public void insertBatch(){
                   SqlSession session = sessionFactory.openSession();
                   Map<String,Object> map = new HashMap<String,Object>();
                   List<Person> pList= new ArrayList<Person>();
                   try {
                            for(int i = 0; i < 1000009; i++){
                                     Person p = new Person();
                                     p.setName("武松"+i);
                                     p.setGender("0");
                                     p.setPersonAddr("陽谷縣");
                                     p.setBirthday(new Date());
                                     pList.add(p);
                                     if(i0 == 0){
                                               map.put("pList", pList);
                                               session.insert("com.rl.mapper.PersonMapper.insertBatch", map);
                                               pList.clear();
                                     }
                            }
                            map.put("pList", pList);
                            session.insert("com.rl.mapper.PersonMapper.insertBatch", map);
                            //庫表的變更都需要提交
                            session.commit();
                   } catch (Exception e) {
                            e.printStackTrace();
                            session.rollback();
                   }finally{
                            session.close();
                   }
         }
        
         @Test
         public void deleteBatch(){
                   SqlSession session = sessionFactory.openSession();
                   Map<String,Object> map = new HashMap<String,Object>();
                   List<Integer> ids= new ArrayList<Integer>();
                   try {
                            for(int i = 106; i < 1000115; i++){
                                     ids.add(i);
                                     if(i0 == 0){
                                               map.put("ids", ids);
                                               session.delete("com.rl.mapper.PersonMapper.deleteBatch", map);
                                               ids.clear();
                                     }
                            }
                            map.put("ids", ids);
                            session.insert("com.rl.mapper.PersonMapper.deleteBatch", map);
                            //庫表的變更都需要提交
                            session.commit();
                   } catch (Exception e) {
                            e.printStackTrace();
                            session.rollback();
                   }finally{
                            session.close();
                   }
         }
}
MybatisTest3.java的內(nèi)容如下:
package com.rl.test;
 
import java.io.InputStream;
 
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.junit.Before;
import org.junit.Test;
 
import com.rl.model1.Orders;
import com.rl.model1.Person;
import com.rl.model1.Role;
 
/**
 * mybatis的關(guān)聯(lián)查詢
 */
public class MybatisTest3 {
 
   SqlSessionFactory sessionFactory;
  
   @Before
   public void setUp() throws Exception {
      InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
      sessionFactory = new SqlSessionFactoryBuilder().build(in);
   }
 
   /**
    * 一對多關(guān)聯(lián)查詢
    */
   @Test
   public void selectPersonAndOrderByPId() {
      //創(chuàng)建session對象
      SqlSession session = sessionFactory.openSession();
      try {
         //第一個參數(shù):指定要執(zhí)行的sql語法是namespace.sql的id痪伦,第二個參數(shù)sql要接收的參數(shù)
         Person person  = session.selectOne("com.rl.mapper.PersonMapper.selectPersonAndOrderByPId", 1);
         System.out.println(person);
      } finally{
         session.close();
      }
   }
  
   /**
    * 查詢Person下的所有訂單和訂單下的明細
    */
   @Test
   public void selectPersonOrderAndDetailByPId() {
      //創(chuàng)建session對象
      SqlSession session = sessionFactory.openSession();
      try {
         //第一個參數(shù):指定要執(zhí)行的sql語法是namespace.sql的id侄榴,第二個參數(shù)sql要接收的參數(shù)
         Person person  = session.selectOne("com.rl.mapper.PersonMapper.selectPersonOrderAndDetailByPId", 1);
         System.out.println(person);
      } finally{
         session.close();
      }
   }
  
   /**
    * 多對多查詢從Person端出發(fā)
    */
   @Test
   public void selectPersonAndRoleByPId() {
      //創(chuàng)建session對象
      SqlSession session = sessionFactory.openSession();
      try {
         //第一個參數(shù):指定要執(zhí)行的sql語法是namespace.sql的id,第二個參數(shù)sql要接收的參數(shù)
         Person person  = session.selectOne("com.rl.mapper.PersonMapper.selectPersonAndRoleByPId", 1);
         System.out.println(person);
      } finally{
         session.close();
      }
   }
  
   /**
    * 多對多查詢從角色端來看
    */
   @Test
   public void selectRoleAndPersonByRId() {
      //創(chuàng)建session對象
      SqlSession session = sessionFactory.openSession();
      try {
         //第一個參數(shù):指定要執(zhí)行的sql語法是namespace.sql的id网沾,第二個參數(shù)sql要接收的參數(shù)
         Role role  = session.selectOne("com.rl.mapper.RoleMapper.selectRoleAndPersonByRId", 1);
         System.out.println(role);
      } finally{
         session.close();
      }
   }
  
   /**
    * 多對一的關(guān)聯(lián)查詢
*這里的mapper配置文件在后續(xù)的博文中定義癞蚕。
    */
   @Test
   public void selectPersonByOrderId() {
      //創(chuàng)建session對象
      SqlSession session = sessionFactory.openSession();
      try {
         Orders order  = session.selectOne("com.rl.mapper.OrdersMapper.selectPersonByOrderId", 1);
         System.out.println(order);
      } finally{
         session.close();
      }
   }
  
   /**
    * 多對一和一對多混合查詢
    * 這里的mapper配置文件在后續(xù)的博文中定義。
    */
   @Test
   public void selectPersonAndDetailByOrderId() {
      //創(chuàng)建session對象
      SqlSession session = sessionFactory.openSession();
      try {
         Orders order  = session.selectOne("com.rl.mapper.OrdersMapper.selectPersonAndDetailByOrderId", 1);
         System.out.println(order);
      } finally{
         session.close();
      }
   }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末辉哥,一起剝皮案震驚了整個濱河市桦山,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌醋旦,老刑警劉巖恒水,帶你破解...
    沈念sama閱讀 212,222評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異饲齐,居然都是意外死亡钉凌,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,455評論 3 385
  • 文/潘曉璐 我一進店門捂人,熙熙樓的掌柜王于貴愁眉苦臉地迎上來御雕,“玉大人,你說我怎么就攤上這事先慷。” “怎么了咨察?”我有些...
    開封第一講書人閱讀 157,720評論 0 348
  • 文/不壞的土叔 我叫張陵论熙,是天一觀的道長。 經(jīng)常有香客問我摄狱,道長脓诡,這世上最難降的妖魔是什么无午? 我笑而不...
    開封第一講書人閱讀 56,568評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮祝谚,結(jié)果婚禮上宪迟,老公的妹妹穿的比我還像新娘。我一直安慰自己交惯,他們只是感情好次泽,可當我...
    茶點故事閱讀 65,696評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著席爽,像睡著了一般意荤。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上只锻,一...
    開封第一講書人閱讀 49,879評論 1 290
  • 那天玖像,我揣著相機與錄音,去河邊找鬼齐饮。 笑死捐寥,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的祖驱。 我是一名探鬼主播握恳,決...
    沈念sama閱讀 39,028評論 3 409
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼羹膳!你這毒婦竟也來了睡互?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,773評論 0 268
  • 序言:老撾萬榮一對情侶失蹤陵像,失蹤者是張志新(化名)和其女友劉穎就珠,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體醒颖,經(jīng)...
    沈念sama閱讀 44,220評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡妻怎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,550評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了泞歉。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片逼侦。...
    茶點故事閱讀 38,697評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖腰耙,靈堂內(nèi)的尸體忽然破棺而出榛丢,到底是詐尸還是另有隱情,我是刑警寧澤挺庞,帶...
    沈念sama閱讀 34,360評論 4 332
  • 正文 年R本政府宣布晰赞,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏掖鱼。R本人自食惡果不足惜然走,卻給世界環(huán)境...
    茶點故事閱讀 40,002評論 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望戏挡。 院中可真熱鬧芍瑞,春花似錦、人聲如沸褐墅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,782評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽掌栅。三九已至秩仆,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間猾封,已是汗流浹背澄耍。 一陣腳步聲響...
    開封第一講書人閱讀 32,010評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留晌缘,地道東北人齐莲。 一個月前我還...
    沈念sama閱讀 46,433評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像磷箕,于是被迫代替她去往敵國和親选酗。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,587評論 2 350

推薦閱讀更多精彩內(nèi)容