Mybatis中常見操作(基本操作+動態sql+sql片段+關聯映射(resultMap))


 

Mapper接口開發需要遵循規范

1.Mapper.xml文件中的namespace與mapper接口的類路徑相同
2.Mapper接口方法名和Mapper.xml中定義的每個statement的id相同
3.Mapper接口方法的輸入參數類型和Mapper.xml中定義的每個sql的parameterType的類型相同
4.Mapper接口方法的輸出參數類型和Mapper.xml中定義的每個sql的resultType的類型相同

MyBatis的配置文件

SqlMapConfig.xml:此文件作為mybatis的全局配置文件,配置了mybatis的運行環境等信息。
mapper.xml:此文件sql映射文件,文件中配置了操作數據庫的sql語句。此文件需要在SqlMapConfig.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" >

<configuration>

<!-- 別名:type:類的全路勁名稱  alias:別名 -->
    <typeAliases> 
        <typeAlias type="cn.itheima.pojo.User" alias="user"/>
        
        <!-- 使用包掃描的方式批量定義別名 定以后別名等於類名,不區分大小寫,但是建議按照java命名規則來,首字母小寫,以后每個單詞的首字母大寫-->
        <package name="com.mybatis.demo01"/>
    </typeAliases>
    
<!-- 讀取java屬性配置文件內容 -->
    <properties resource="db.properties"></properties>
    <environments default="development">
        <environment id="development">
        <transactionManager type="JDBC" />
        <dataSource type="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>
    
    
<!-- 加載映射文件 class:接口的全路徑    resource:配置文件-->
    <mappers>
        <mapper class="com.mybatis.demo01.UserMapper" />
        <mapper resource="sqlmap/UserMapper.xml"/>
        <!-- 注冊指定包下的所有mapper接口 -->
        <package name="com.mybatis.demo01" />
    </mappers>
</configuration>

 

Mapper配置文件內容

<?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="com.mybatis.demo.UserDao">
    <!-- mapper里面寫數據庫操作的語句-->
    
</mapper>

1.簡單數據庫操作

public class User {
    private int id;
    private String username;// 用戶姓名
    private String sex;// 性別
    private Date birthday;// 生日
    private String address;// 地址
     
        getset。。。        
}

 

<?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="com.mybatis.demo01.UserDao">

    <!-- 1.根據id獲取用戶信息 -->
    <select id="findUserById" parameterType="int" resultType="com.mybatis.demo01.User">
        seletct * from user where id = #{id}
    </select>
    
    <!-- 2.根據用名模糊查詢用戶信息表 -->
    <select id="findUserByUsername" parameterType="java.lang.String" resultType="com.mybatis.demo01.User">
        select * from user where username like '%${value}%'
    </select>
    
    <!-- 3.添加用戶 -->
    <insert id="insertUser" parameterType="com.mybatis.demo01.User" keyProperty="id" resultType="java.lang.Integer">
        insert into user(username,birthday,sex,address)
        values(#{username},#{birthday},#{sex},#{address})
    </insert>
    
    <!-- 4.刪除用戶 -->
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>
    
    <!-- 5.修改用戶 -->
    <update id="updateUser" parameterType="com.mybatis.demo01.User">
        update user set
        username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
        where id=#{id}
    </update>
    
    <!-- 6.獲取用戶類別總數 -->
    <select id="findUserCount" parameterType="user" resutlType="int">
        select count(1) from user
    </select>    
    
    <!-- 7.獲取所有用戶列表 -->
    <select id="findAll" resultType="com.mybatis.demo01.User">
        select * from user
    </select>

</mapper>

 

2.動態sql語句

<?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" >

<!-- 動態sql語句:if,where,set,foreach -->
<mapper namespace="com.mybatis.demo01.UserDao">


    <!-- 1.根據用戶名模糊查詢用戶信息表:if和where -->
    <select id="findUserList" parameterType="user" resultType="user">
        select * from user
        <where>
            <if test="id!=null">
                and id=#{id}
            </if>
            <if test="username!=null and username!='' ">
                and username like '%${username}%'
            </if>
        </where>        
    </select>
    
    <!-- 2.根據用戶id批量查詢用戶:foreach -->
    <select id="findUserIds" parameterType="int" resultType="user">
        select * from user
        <if test="ids!=null and ids.size>0">
            <!-- 批量拼接 -->
            <foreeach coolection="id" open="and id in(" close=")" item="id" separator=",">
                #{id}
            </foreeach>
        </if>
    </select>
    
</mapper>
<?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="com.test.dao.user.PersonDao">
    <!-- 增加實體 -->
    <insert id="insertPerson" useGeneratedKeys="true" keyProperty="id">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="name !=null">name,</if>
            <if test="age != 0">age,</if>
            <if test="sex !=null">sex</if>
        </trim>
        values
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="name !=null">#{name},</if>
            <if test="age != 0">#{age},</if>
            <if test="sex !=null">#{sex}</if>
        </trim>
    </insert>
    
    <!-- 查詢 條件-->
    <select id="selectPerson" resultType="com.test.model.user.Person">
        select * from user 
        <where>
            <if test="id!=null">id = #{id}</if>
            <if test="id!=null">and name = #{name}</if>
            <if test="id!=null">and age = #{age}</if>
        </where>
    </select>
    
    <!-- 查詢所有 -->
    <select id="selectAll" resultType="com.test.model.user.Person">
        select * from user
    </select>
    
    <!-- 更新 -->
    <update id="update">
        update user 
        <set>
            <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>
            <if test="birthday!=null">birthday=#{birthday},</if>
            <if test="salary!=null">salary=#{salary},</if>
            <if test="createTime!=null">createTime=#{createTime},</if>
        </set>
        where id = #{id}
    </update>
    
    <!-- 刪除 -->
    <delete id="deleteOne">
        delete from user
        <where>
            <if test="id != null">id=#{id}</if>
            <if test="name != null">and name=#{name}</if>
            <if test="age != null">and age=#{age}</if>
        </where>
    </delete>
    
    <!-- 批量刪除 -->
    <delete id="deleteMany">
        delete from user where id in
        <foreach collection="list" open="(" close=")" separator="," item="id">
            #{id}
        </foreach>
    </delete>
    
</mapper>

 

3.Sql片段

<?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">

<!-- sql片段:重復的部分提取重用 -->
<mapper namespace="com.mybatis.demo01.UserDao">

    <sql id="query_user_where">
        <if test="id!=null and id!=''">
            and id=#{id}
        </if>
        <if test="username!=null and useraname!=''">
            and username like '%${username}%'
        </if>
    </sql>
    
    <select id="findUserList" parameterType="user" resultType="user">
        select * from user
        <where>
            <!-- 插入上面的sql片段 -->
            <include refid="query_user_where" />
        </where>
    </select>

</mapper>

 

4.關聯映射(resultMap)

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

如果sql查詢字段名和pojo的屬性名不一致,可以通過resultMap將字段名和屬性名作一個對應關系,resultMap實在上還需要將查詢結果映射到pojo對象中。

resultMap可以試下將查詢結果映射為復雜類型的pojo,比如在查詢結果映射對象中包括pojo和list實現一對一查詢和一對多查詢。

Orders:

public class Orders {
    private Integer id;
    private Integer userId;
    private String number;
    private Date createtime;
    private String note;
    private User user;

    getset.....
}

User:

public class User {
    private int id;
    private String username;// 用戶姓名
    private String sex;// 性別
    private Date birthday;// 生日
    private String address;// 地址
    private List<Orders> ordersList;
        
        getset....
}

Mapper:

<?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" >

<!-- resultMap:一對一關聯映射,一對多關聯映射 -->
<mapper namespace="com.mybatis.demo01.UserDao">

    <!-- 一對一關聯查詢 -->
    <resultMap type="Orders" id="orderUserResultMap">
            <!-- Orders類中的基本類型:id是orders類的主鍵對應的屬性,result是其他屬性 -->
            <id column="id" property="id" />
            <result column="user_id" property="userId" />
            <result column="number" property="number" />
            <result column="createtime" property="createtime" />
            <result column="note" property="note" />
            <!-- Orders類中的User類的對象:同樣id是User類對應user表的主鍵,result是其他基本類型 -->
            <association property="user" javaType="com.mybatis.demo01.User">
                <id column="user_id" property="id"/>
                <result column="username" property="username" />
                <result column="address" property="address" />
            </association>
    </resultMap>
    <select id="findOrdersWithUserResultMap" resultMap="orderUserResultMap">
        select o.id,o.user_id,o.number,o.note,u.username,u.address
        from 
        orders o join user u on u.id=o.user_id
    </select>
    
    <!-- 一對多關聯查詢 -->
    <resultMap type="user" id="userOrderResultMap">
        <!-- 用戶信息映射 -->
        <id property="id" column="id" />
        <result property="username" property="username"/>
        <result property="birthday" property="birthday"/>
        <result property="sex" property="sex"/>
        <result property="address" property="address"/>
        <!-- 一對多關聯映射 -->
        <collection property="orders" ofType="orders">
            <id property="id" column="oid"/>
            <!-- <result property="userId" column="id"/> 用戶id已經在user對象存在,不用設置 -->
            <result property="number" column="number"/>
            <result property="createtime" column="createtime"/>
            <result property="note" column="note"/>
        </collection>
    </resultMap>
    <select id="getUserOrderList" resultMap="userOrderResultMap">
        select u.*,o.id oid,o.number,o.createtime,o.note from user u 
        left join orders o on u.id = o.user_id
    </select>
    
</mapper>

 

 

1.namespace:命名空間,用於隔離sql語句,一般使用對應接口文件全路徑名
2.parameterType:定義輸入到sql中的映射類型
3.resultType:定義結果映射類型
4.#{id}表示占位符,將輸入變量id傳到sql
5.${value}表示字符串的拼接符,如果參數時基本數據類型,口號中的值必須value
6.插入數據是通過keyProperty配置自增主鍵
7.<where>可以自動和處理第一個and


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM