MyBatis01

Mybatis框架的學習

在這裏插入圖片描述

在這裏插入圖片描述

SqlMapperConfig.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>
    <!-- 環境,可以配置多個,default:指定採用哪個環境 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="test">
        <!-- id:唯一標識 -->
        <environment id="test">
            <!-- 事務管理器,JDBC類型的事務管理器 -->
            <transactionManager type="JDBC" />
            <!-- 數據源,池類型的數據源 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/testmybatis?serverTimezone=GMT%2B8" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>

        <environment id="development">
            <!-- 事務管理器,JDBC類型的事務管理器 -->
            <transactionManager type="JDBC" />
            <!-- 數據源,池類型的數據源 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--加載映射文件-->
    <mappers>
        <mapper resource="mappers/MyMapper.xml" />
    </mappers>
</configuration>
XXXmapper.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:命名空間,隨便寫,一般保證命名空間唯一,在使用代理方法開發的時候,namespace 有特殊的意義 -->
<mapper namespace="MyMapper">
    <!-- id==statement的id,內容:sql語句。將來sql語句會封裝到mappedstatement對象當中。id:唯一標識,隨便寫,在同一個命名空間下保持唯一,resultType:sql語句查詢結果集的封裝類型,tb_user即爲數據庫中的表
     -->
    <select id="selectUser" parameterType="int" resultType="www.com.inone.pojo.User" >
      select * from tb_user where id = #{id}
      <!--#{}表示一個佔位符 id表示接收輸入的參數 resultType表示sql輸出的結果映射成pojo,parameterType參數類型 -->
   </select>
	
	<!--${value}:接收輸入參數的內容,拼接符。如果傳入的值是簡單類型則只能使用value-->
	<select id="findUserByName" parameterType="String" resultType="www.com.inone.pojo.User">
        select * from tb_user where user_name LIKE '%{value}%'
	</select>
    <insert id="insertUser" parameterType="www.com.inone.pojo.User">
        insert into tb_user (id,user_name,password,name,age,sex)value (#{id},#{userName},#    {password},#{name},#{age},#{sex} )
    </insert>

</mapper>
配置文件的記載過程
//創建輸入流
String resource = "SqlMapConfig.xml";
InputStream inputStrean=Resources.getResourceAsStrean(resource);
// 創建會話工廠
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder.builde(inputStream);

自增主鍵的返回

將插入的主鍵進行返回,只適用於主鍵的自增。
keyProperty:將查詢到的結果設置到parameterType指定的對象的哪個屬性中
order:指的是執行的順序
在這裏插入圖片描述

非自增主鍵的返回

使用mysql的uuid()函數生主鍵,需要修改表中的id字段爲string類型,並且指定長度爲35位

使用mysql的uuid
// An highlighted block
<!--先通過uuid()獲取主鍵,然後設置到mysql數據庫當中-->
 <insert id="insertUser" parameterType="www.com.inone.pojo.User">
        <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Integer">
            SELECT UUID()
        </selectKey>
        insert into tb_user (id,user_name,password,name,age,sex)value (#{id},#{userName},#{password},#{name},#{age},#{sex} )
    </insert>

總結:
1、#{}表示一個佔位符,類型可以是簡單的類型,pojo,hashmap,如果接受的是簡單的類型,#{}中可以寫成value或其他的名稱
2、&{}表示一個拼接符號,會引入sql的注入,所以不建議使用,接受的參數可以是pojo,hashmap,如果接收的是基本類型則只能使用value

mybatis和hibernate的區別和應用場景

1、hibernate:是一個標準的ORM,入門門檻比較高,不用寫sql語句和jpa差不多。

  • 適用於需求變化不多的中小型的項目:OA /ORM/ERP 等等
    2、mybatis需要我們可以自己編寫sql語句。(不完全的ORM項目)
  • 主要應用於需求變化較多的項目:互聯網的項目等等

只通風mapper接口進行增刪查改的操作

話不多說直接上代碼

1、創建mapper接口
package www.com.inone.userdao;

import org.apache.ibatis.annotations.Param;
import www.com.inone.pojo.User;

import java.util.List;

/**
 * @Auther: ZQB
 * Date:2019/12/12
 */
public interface UserMapper {
    /**
     * 登錄(直接使用註解指定傳入參數名稱)
     * @param userName
     * @param password
     * @return
     */
    public User login(@Param("userName") String userName, @Param("password") String password);

    /**
     * 根據表名查詢用戶信息(直接使用註解指定傳入參數名稱)
     * @param tableName
     * @return
     */
    public List<User> queryUserByTableName(@Param("tableName") String tableName);

    /**
     * 根據Id查詢用戶信息
     * @param id
     * @return
     */
    public User queryUserById(Long id);

    /**
     * 查詢所有用戶信息
     * @return
     */
    public List<User> queryUserAlls();

    /**
     * 新增用戶信息
     * @param user
     */
    public void insertUser(User user);

    /**
     * 根據id更新用戶信息
     * @param user
     */
    public void updateUser(User user);

    /**
     * 根據id刪除用戶信息
     * @param id
     */
    public void deleteUserById(Long id);

}

2、創建配置文件
<?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:命名空間,隨便寫,一般保證命名空間唯一 ,爲了使用接口動態代理,這裏必須是接口的全路徑名-->
<mapper namespace="www.com.inone.userdao.UserMapper">
    <!--
       1.#{},預編譯的方式preparedstatement,使用佔位符替換,防止sql注入,一個參數的時候,任意參數名可以接收
       2.${},普通的Statement,字符串直接拼接,不可以防止sql注入,一個參數的時候,必須使用${value}接收參數
     -->
    <select id="queryUserByTableName" resultType="www.com.inone.pojo.User">
        select * from ${tableName}
    </select>

    <select id="login" resultType="www.com.inone.pojo.User">
        select * from tb_user where user_name = #{userName} and password = #{password}
    </select>

    <!-- statement,內容:sql語句。
       id:唯一標識,隨便寫,在同一個命名空間下保持唯一,使用動態代理之後要求和方法名保持一致
       resultType:sql語句查詢結果集的封裝類型,使用動態代理之後和方法的返回類型一致;resultMap:二選一
       parameterType:參數的類型,使用動態代理之後和方法的參數類型一致
     -->
    <select id="queryUserById" resultType="www.com.inone.pojo.User">
        select * from tb_user where id = #{id}
    </select>
    <select id="queryUserAlls" resultType="www.com.inone.pojo.User">
        select * from tb_user
    </select>
    <!-- 新增的Statement
       id:唯一標識,隨便寫,在同一個命名空間下保持唯一,使用動態代理之後要求和方法名保持一致
       parameterType:參數的類型,使用動態代理之後和方法的參數類型一致
       useGeneratedKeys:開啓主鍵回寫
       keyColumn:指定數據庫的主鍵
       keyProperty:主鍵對應的pojo屬性名
     -->
    <insert id="insertUser" useGeneratedKeys="true" keyColumn="id" keyProperty="id"
            parameterType="www.com.inone.pojo.User">
        INSERT INTO tb_user (
        id,
        user_name,
        password,
        name,
        age,
        sex,
        birthday,
        created,
        updated
        )
        VALUES
        (
        null,
        #{userName},
        #{password},
        #{name},
        #{age},
        #{sex},
        #{birthday},
        NOW(),
        NOW()
        );
    </insert>
    <!--
       更新的statement
       id:唯一標識,隨便寫,在同一個命名空間下保持唯一,使用動態代理之後要求和方法名保持一致
       parameterType:參數的類型,使用動態代理之後和方法的參數類型一致
     -->
    <update id="updateUser" parameterType="www.com.inone.pojo.User">
        UPDATE tb_user
        <trim prefix="set" suffixOverrides=",">
            <if test="userName!=null">user_name = #{userName},</if>
            <if test="password!=null">password = #{password},</if>
            <if test="name!=null">name = #{name},</if>
            <if test="age!=null">age = #{age},</if>
            <if test="sex!=null">sex = #{sex},</if>
            <if test="birthday!=null">birthday = #{birthday},</if>
            updated = now(),
        </trim>
        WHERE
        (id = #{id});
    </update>
    <!--
       刪除的statement
       id:唯一標識,隨便寫,在同一個命名空間下保持唯一,使用動態代理之後要求和方法名保持一致
       parameterType:參數的類型,使用動態代理之後和方法的參數類型一致
     -->
    <delete id="deleteUserById" parameterType="java.lang.String">
        delete from tb_user where id=#{id}
    </delete>
</mapper>

3、添加主配置文件中
<?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>
    <!-- 環境,可以配置多個,default:指定採用哪個環境 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="test">
        <!-- id:唯一標識 -->
        <environment id="test">
            <!-- 事務管理器,JDBC類型的事務管理器 -->
            <transactionManager type="JDBC" />
            <!-- 數據源,池類型的數據源 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/testmybatis?serverTimezone=GMT%2B8" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>

        <environment id="development">
            <!-- 事務管理器,JDBC類型的事務管理器 -->
            <transactionManager type="JDBC" />
            <!-- 數據源,池類型的數據源 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers/MyMapper.xml" />
        <mapper resource="mappers/UserDaoMapper.xml"/>
        <mapper resource="mappers/UserMapper.xml"/>
    </mappers>
</configuration>
4、測試
package www.com.inone.userdao;

import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import www.com.inone.pojo.User;
import www.com.inone.utils.SessFactoryUtil;

import java.util.List;

/**
 * @Auther: ZQB
 * Date:2019/12/12
 */
public class UserMapperTest {
    public UserMapper userMapper;

    @Before
    public void setUp() throws Exception {
        // 指定配置文件
        SqlSession sqlSession= SessFactoryUtil.getSession();
        // 1. 映射文件的命名空間(namespace)必須是mapper接口的全路徑
        // 2. 映射文件的statement的id必須和mapper接口的方法名保持一致
        // 3. Statement的resultType必須和mapper接口方法的返回類型一致
        // 4. statement的parameterType必須和mapper接口方法的參數類型一致(不一定)
        this.userMapper = sqlSession.getMapper(UserMapper.class);
    }
    @Test
    public void testQueryUserAll() {
        List<User> userList = this.userMapper.queryUserAlls();
        for (User user : userList) {
            System.out.println(user);
        }
    }
    @Test
    public void testDeleteUserById() {
        this.userMapper.deleteUserById(1l);
    }

}
  • 注意:1、命名空間的i值一定要是mapper接口的全路徑。
  • 2、mapper.xml增刪查改的id值一定要和mapper接口中的增刪查改的方法名相同.
  • 3、在主配置文件中添加

對主配置文件的學習

// A code block
<?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 resource="application.properties"></properties>
 <!--設置pojo和數據表相互對應-->
  <settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>
  <typeAliases>
        <!--type:類的全名 alis:別名-->
        <typeAlias type="www.com.inone.pojo.User" alias="user"></typeAlias>
    </typeAliases>
  <!--環境可以寫多個-->
   <environments default="development">
        <environment id="test">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/testmybatis?serverTimezone=GMT%2B8" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>
</configuration>

typeAliases(別名,重點)

在mapper.xml中,定義了很多的statement,statement需要parameterType指定輸入參數的類型,需要resultType指定輸出的映射類型。

如果在指定類型時輸入類型全路徑,不方便進行開發,可以針對parameterType和resultType指定的類型定義一些別名,在mappper.xml通過別名定義,方便開發。

《單個別名》

<typeAliases>
  	 type:實體類的全路徑。alias:別名,通常首字母小寫
    <typeAlias type="www.com.inone.pojo.Userr" alias="User"/>
</typeAliases>

《批量別名》

<typeAliases>
    <package name="www.com.inone.pojo"/>
</typeAliases>

Mybatis已經爲普通的 Java 類型內建了許多相應的類型別名。它們都是大小寫不敏感的.

通過mapper接口加載映射文件

通過mapper接口加載映射文件
規範:1、需要將mapper接口類名和mapper.xml映射文件名稱保持一致且在同一個目錄當中
在這裏插入圖片描述
2、使用mapper接口代理的方式

  • 注意:可能出現的問題:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): www.com.inone.userdao.UserMapper.queryUserAll

如果我們的mapper.xml文件沒有放置到src-main-resources下面,是不會被maven build plugin給默認掃描到的。此時需要修改啓動的模塊的pom文件,在build標籤裏面加入:
解決方法:在pom文件加入:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
  • 單獨加載mapper
    在這裏插入圖片描述
  • 批量加載
    在這裏插入圖片描述

傳遞pojo的包裝對象

在這裏插入圖片描述在這裏插入圖片描述
在這裏插入圖片描述

resultType可以指定pojo將查詢的結果映射爲pojo,但需要pojo的屬性名和sql查詢的列名一致方可映射成功!

ResultMap的簡單使用

mybatis中使用resultMap來完成高級映射。
如果查詢出來的列名和pojo的屬性名不一致,通過定義一個resultMap對列名和pojo屬性名做一個映射關係。
使用步驟:
1、定義ResultMap

   <resultMap id="userResultMap" type="user">
        <!--唯一主鍵列的映射-->
        <!--id:查詢結果的唯一表示  property:pojo的屬性名-->
        <id column="id_" property="id"></id>
        <!--其他屬性列的映射-->
        <result column="username_" property="userName"></result>
    </resultMap>

2、使用ResultMap作爲statement的輸出類型

    <!--resitMap:指定定義的resultMap,如果這個resultMap在其他的mapper.xml文件中,則前面需要加namespace-->
    <select id="findUserByIdMap" parameterType="int"  resultMap="userResultMap">
        select id id_,user_name username_ from tb_user where id=#{value}
    </select>

動態sql

  • if where
// An highlighted block
 <select id="findUserList" parameterType="UserQueryVo" resultType="UserCustom">
        select * from tb_user
        <where>
            <if test="userCustom!=null">
                <if test="userCustom.sex!=null and userCustom.sex!=''">
                   and tb_user.sex=#{userCustom.sex}
                </if>
                <if test="userCustom.userName!=null and  userCustom.userName!=''">
                   and tb_user.user_name like '%${userCustom.userName}%'
                </if>
            </if>
        </where>
    </select>
  • sql 片段
 <sql id=””></sql>
<include refId=”” />
  • foreach
/**
 * 按多個Id查詢
 * @param ids
 * @return
 */
List<User> queryUserListByIds(@Param("ids") String[] ids);
<select id="queryUserListByIds" resultType="com.zpc.mybatis.pojo.User">
    select * from tb_user where id in
    <!--collection:指定輸入對象中集合屬性 item:每個遍歷生成的id,open:開始遍歷拼接的串 close:結束遍歷拼接的串-->
    《!--select * from tb_user where tb_user.user_name LIKE '%${value}%' AND (id=? or id =? or id=? )--<foreach collection="ids" item="id_item" open="AND (" close=")" separator="or">
        id=#{id_iten}
    </foreach>
</select>
————————————————

原文鏈接:https://blog.csdn.net/hellozpc/article/details/80878563

————————————————
參考原文鏈接:https://blog.csdn.net/hellozpc/article/details/80878563
參考原文鏈接:https://www.jianshu.com/p/a9516bcd3cb0
參考原文鏈接:https://www.cnblogs.com/huanghuanghui/p/9836765.html
參考原文鏈接:http://blog.csdn.net/isea533/article/details/73555400

發佈了22 篇原創文章 · 獲贊 6 · 訪問量 666
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章