2. MyBatis-CRUD

UnityAlvin發表於2020-12-01

示例

UserMapper.xml

<mapper namespace="com.indi.dao.UserMapper">
    <!--
        namespace 		繫結一個對應的Mapper
        id  			對應Mapper的方法名
        parameterType 	引數型別
        resultType 		SQL語句的返回值
        引數用#{}填寫
    -->

    <select id="getUserList" resultType="com.indi.pojo.User">
        select * from mybatis.user;
    </select>

    <select id="getUserById" resultType="com.indi.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>

    <!--物件中的屬性,直接寫-->
    <insert id="addUser" parameterType="com.indi.pojo.User">
        insert into mybatis.user(id, name, pwd) value (#{id},#{name},#{pwd});
    </insert>

    <update id="updateUser" parameterType="com.indi.pojo.User">
        update mybatis.user set name = #{name},pwd=#{pwd} where id =#{id};
    </update>

    <delete id="deleteUserById" parameterType="int">
        delete from mybatis.user where id = #{id};
    </delete>
</mapper>

增刪改操作完之後必須要提交事務!

萬能Map

如果實體類、或者資料庫中的表,欄位或者引數過多,應當考慮使用Map

UserMapper.java

public interface UserMapper {
    int updateUserPassword(Map<String,Object> map);
}

UserMapper.xml

    <update id="updateUserPassword" parameterType="map">
        update mybatis.user set pwd=#{password} where id =#{id};
    </update>

UserMapperTest.java

    @Test
    public void updateUserPassword() {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("id",5);
        map.put("password","666330");

        userMapper.updateUserPassword(map);

        sqlSession.commit();
        sqlSession.close();
    }
  • parameterType="map",傳遞引數為Map時,直接在SQL中取出key即可
  • parameterType="Object",傳遞引數為物件時,直接取物件的屬性即可
  • parameterType=“int”,可省略,只有一個基本型別的引數時,可直接在SQL中取到
  • 多個引數用Map,或註解

模糊查詢

  1. 在執行傳參的時候加上萬用字元
        userMapper.getUserByName("%q%").forEach(System.out::println);
  1. 在SQL中加上萬用字元
    <select id="getUserByName" resultType="com.indi.pojo.User">
        select * from mybatis.user where name like "%"#{name}"%"
    </select>