1. 程式人生 > >分享知識-快樂自己:Mybatis 基礎動態語句

分享知識-快樂自己:Mybatis 基礎動態語句

目錄:

User:

package mlq.bean;

/**
 * 使用者實體類
 */
public class User {

  private Integer uId;
  private String userName;
  private String userPwd;
  private String realName;

  public User(Integer uId, String userName, String userPwd, String realName) {
    this.uId = uId;
    this.userName = userName;
    
this.userPwd = userPwd; this.realName = realName; } public User(Integer uId) { this.uId = uId; } public User() { } @Override public String toString() { return "User{" + "uId=" + uId + ", userName='" + userName + '\'' + ", userPwd='" + userPwd + '\'' + ", realName='" + realName + '\'' + '}'; }
}

UserMappers:

package mlq.Mapper;

import mlq.bean.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

/**
 * 使用者介面
 */
public interface UserMappers {

    /**
     * 查詢使用者資訊
     */
    public List<User> userAllList(User user);
    
public List<User> userAllListTow(User user); public List<User> userAllListChoose(User user); /** * 更新使用者資訊 */ public int updUser(User user); public int updUserTow(User user); /** * 使用陣列入參Foreach遍歷 * @param ars * @return */ public List<User> userArrays(int[] ars); /** * 使用List普通入參Foreach遍歷 * @param ars * @return */ public List<User> userListForeach(List<String> ars); /** * 使用List物件入參Foreach遍歷 * @param ars * @return */ public List<User> userListForeachs(List<User> ars); /** * 使用Map+List集合入參Foreach遍歷 * @param ars * @return */ public List<User> userMapForeach(Map<String,Object> ars); /** * 使用Map入參Foreach遍歷 * @param ars * @return */ public List<User> userMap(Map<String,Object> ars); public List<User> userMapTow(@Param("ars") Map<String,User> ars); /** * 同時插入多條資料 * @param list * @return */ public int inserUsers(List<User> list); }

MyBatis.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!---->
<configuration>

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

    <!--設定類別名-->
    <typeAliases>
        <package name ="mlq.bean" />
    </typeAliases>

    <!--設定Mybatis執行環境-->
    <environments default="mysql"><!--default找到環境的id,只能用一個-->
        <environment id="mysql"><!--可以定義多個環境-->
            <transactionManager type="JDBC"/><!--後續事務的管理 統一交給spring容器-->
            <dataSource type="POOLED"><!--資料來源 Tomcat:JNDI Mybatis:POOLED-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

MyBatisTool:

package mlq.util;

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 java.io.IOException;
import java.io.Reader;

/**
 * 獲取連線物件工具類
 */
public class MyBatisTool {

    //建立私有構造
    private  MyBatisTool(){}

    //SQLSessionFactory 簡單的理解就是建立SQLSession 例項的工廠。
    private final static SqlSessionFactory sqlSessionFactory;

    //靜態程式碼塊初始化sqlSessionFactory物件
    static
    {
        //獲取Mybatis.xml核心配置檔案路徑
        String path="MyBatis.xml";
        Reader reader=null;
        try {
            //將檔案資訊讀取到記憶體中
             reader = Resources.getResourceAsReader(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //建立例項
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
    }

    /**
     * 獲取工廠函式SQLSessionFactory
     * @return
     */
   public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; }

    /**
     * 獲取SqlSession連線物件
     * @return
     */
   public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();}

    /**
     * 關閉連線物件
     * @param sqlSession
     */
   public static void closeSqlsession(SqlSession sqlSession){
       if (sqlSession!=null)
       {
           sqlSession.close();
       }
   }
}

UserMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mlq.Mapper.UserMappers">


    <!--使用Where標籤實現動態SQL拼接-->
    <select id="userAllListTow" parameterType="User" resultType="User">
        SELECT * FROM `user` WHERE 1=1
        <if test="userName!=null and userName!=''">
            AND `userName`=#{userName}
        </if>
        <if test="userPwd!=null and userPwd!=''">
            AND `userPwd`=#{userPwd}
        </if>
        <if test="uId!=null and uId!=''">
            AND `uId`=#{uId}
        </if>
    </select>

    <!--使用Where標籤實現動態SQL拼接-->
    <select id="userAllList" parameterType="User" resultType="User">
        SELECT * FROM `user`
        <where>
            <if test="userName!=null and userName!=''">
                AND `userName`=#{userName}
            </if>
            <if test="userPwd!=null and userPwd!=''">
                AND `userPwd`=#{userPwd}
            </if>
            <if test="uId!=null and uId!=''">
                AND `uId`=#{uId}
            </if>
        </where>
    </select>

    <!--使用SET標籤更新資料:說明此番操作有漏洞。逗號位置不明確:建議使用下述方式-->
    <update id="updUser" parameterType="User">
        UPDATE `user`
        <set>
            <if test="userName!=null and userName!=''">
                `userName`=#{userName},
            </if>
            <if test="userPwd!=null and userPwd!=''">
                `userPwd`=#{userPwd},
            </if>
            <if test="realName!=null and realName!=''">
                `realName`=#{realName},
            </if>
        </set>
        <where>
            `uId`=#{uId}
        </where>
    </update>
    <update id="updUserTow" parameterType="User">
        UPDATE `user`
        <trim prefix="set" suffixOverrides="," suffix="`uId`=#{uId}">
            <if test="userName!=null and userName!=''">
                `userName`=#{userName},
            </if>
            <if test="userPwd!=null and userPwd!=''">
                `userPwd`=#{userPwd},
            </if>
            <if test="realName!=null and realName!=''">
                `realName`=#{realName},
            </if>
        </trim>
    </update>

    <!--公用SQL片段-->
    <sql id="cols"> SELECT * FROM `user`</sql>
    <!--使用choose方式判斷:相當於switch結構-->
    <select id="userAllListChoose" parameterType="User" resultType="User">
        <include refid="cols"/>
        <where>
            <choose>
                <when test="userName!=null and userName!=''">
                    AND `userName`=#{userName}
                </when>
                <when test="userPwd!=null and userPwd!=''">
                    AND `userPwd`=#{userPwd}
                </when>
                <otherwise>
                    AND `uId`=#{uId}
                </otherwise>
            </choose>
        </where>
    </select>

    <!--使用陣列入參,Foreach遍歷-->
    <select id="userArrays" resultType="User">
        <include refid="cols"/>
        <trim prefix="where `uId` in">
            <if test="array.length>0">
                <foreach item="temp" collection="array" open="(" close=")" separator=",">
                    #{temp}
                </foreach>
            </if>
        </trim>
    </select>
<!--使用List普通入參,Foreach遍歷-->
    <select id="userListForeach" resultType="User">
        <include refid="cols"/>
        <trim prefix="where `uId` in">
            <if test="list.size>0">
                <foreach item="temp" collection="list" open="(" close=")" separator=",">
                    #{temp}
                </foreach>
            </if>
        </trim>
    </select>
<!--使用List物件入參,Foreach遍歷-->
    <select id="userListForeachs" resultType="User">
        <include refid="cols"/>
        <trim prefix="where `uId` in">
            <if test="list.size>0">
                <foreach item="temp" collection="list" open="(" close=")" separator=",">
                    #{temp.uId}
                </foreach>
            </if>
        </trim>
    </select>
<!--使用Map+List集合入參-->
    <select id="userMapForeach" resultType="User">
        <include refid="cols"/>
        <where>
            <if test="mapList.size>0">
                `uId` in
                <foreach collection="mapList" open="(" close=")" item="temp" separator=",">
                    #{temp}
                </foreach>
            </if>
        </where>

    </select>

    <select id="userMap" resultType="User">
        <include refid="cols"/>
        <where>
            `uId` in (#{one})
        </where>
    </select>
    <!--使用註解入參Map-->
    <select id="userMapTow" resultType="User">
        <include refid="cols"/>
        <where>
            `uId` in
            <if test="ars.keys.size>0">
                <foreach collection="ars.keys" open="(" separator="," close=")" item="key" index="ind">
                    <!--通過鍵獲取value-->
                    #{ars[${key}].uId}
                    <!--直接獲取key-->
                    <!--#{key}-->
                </foreach>
            </if>
        </where>
    </select>


</mapper>

UserText:

package mlq;

import mlq.bean.User;
import mlq.Mapper.UserMappers;
import mlq.util.MyBatisTool;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserText {

    //連線SQLSession
    private SqlSession sqlSession = null;
    private UserMappers mapper = null;

    //測試前置增強
    @Before
    public void before() {
        sqlSession = MyBatisTool.getSqlSession();
        mapper = sqlSession.getMapper(UserMappers.class);
    }

    //測試後置增強
    @After
    public void after() {
        sqlSession.commit();
        sqlSession.close();
    }

    /**
     * 查詢使用者資訊
     */
    @Test
    public void userAllList() {
        User user = new User();
        user.setUserName("MLQ");
        user.setUId(20180001);
        List<User> users = mapper.userAllList(user);
        System.out.println(users);
    }

    @Test
    public void userAllListTow() {
        User user = new User();
        user.setUserName("MLQ");
        user.setUId(20180001);
        List<User> users = mapper.userAllListTow(user);
        System.out.println(users);
    }

    @Test
    public void userAllListChoose() {
        User user = new User();
        user.setUserName("FKX");
        user.setUId(20180002);
        List<User> users = mapper.userAllListChoose(user);
        System.out.println(users);
    }

    /**
     * 更新使用者資訊
     */
    @Test
    public void updUser() {
        User user = new User();
        user.setRealName("MLQMLQ");
        user.setUserPwd("456");
        user.setUserName("MLQ");
        user.setUId(20180001);
        int i = mapper.updUser(user);
        System.out.println((i > 0) ? "更新成功" : "更新失敗!!!");
    }

    @Test
    public void updUserTow() {
        User user = new User();
        user.setRealName("MLQ");
        user.setUserPwd("123");
        user.setUserName("MLQ");
        user.setUId(20180001);
        int i = mapper.updUser(user);
        System.out.println((i > 0) ? "更新成功" : "更新失敗!!!");
    }

    /**
     * 使用陣列入參Foreach遍歷
     */
    @Test
    public void arrayList() {
        int[] ars = {20180001, 20180002};
        List<User> users = mapper.userArrays(ars);
        System.err.println(users);
    }

    /**
     * 使用List入參Foreach遍歷
     */
    @Test
    public void userListForeach() {
        List<String> list = new ArrayList<String>();
        list.add("20180001");
        list.add("20180002");
        List<User> users = mapper.userListForeach(list);
        System.out.println(users);
    }

    @Test
    public void userListForeachs() {
        List<User> list = new ArrayList<User>();
        User user = new User();
        user.setUId(20180001);
        User user1 = new User();
        user1.setUId(20180002);
        list.add(user);
        list.add(user1);
        List<User> users = mapper.userListForeachs(list);
        System.err.println(users);
    }

    //使用Map集合入參Foreach遍歷
    @Test
    public void userMapForeach() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Integer> list = new ArrayList<Integer>();
        list.add(20180001);
        list.add(20180002);
        map.put("one", 20180001);
        map.put("mapList", list);
        List<User> users = mapper.userMapForeach(map);
        System.err.println(users);
    }

    //使用Map集合入參Foreach遍歷
    @Test
    public void userMap() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Integer> list = new ArrayList<Integer>();
        list.add(20180001);
        list.add(20180002);
        map.put("one", 20180001);
        map.put("mapList", list);
        List<User> users = mapper.userMap(map);
        System.err.println(users);
    }

    /**
     * 入參Map集合使用註解標註資訊
     */
    @Test
    public void userMapTow() {
        Map<String, User> map = new HashMap<String, User>();
        User user = new User(20180001);
        User user1 = new User(20180002);
        map.put("20180001", user);
        map.put("20180002", user1);
        List<User> users = mapper.userMapTow(map);
        System.err.println(users);
    }
}

案例Demo下載:Day02中的Maven