Mybatis基本使用(一)

1. 基本配置(這裏強調的重點不在於配置細節,而在於 .dtd 文件的引用位置)
  1. mybatis.config.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 resource="conf/mysql.properties">
  </properties>

  <environments default="development">
    <environment id="development">
      <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="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
  1. mapper.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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
  1. 一些語句示例
<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username, password, email, bio) values
  <foreach item="item" collection="list" separator=",">
    (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
  </foreach>
</insert>

# public void deleteById(int id,int name);
<delete id="deleteById" parameterType="java.lang.Integer">
		delete from `T_aaaa` where id=#{0} and name=#{1}
</delete>

# public List<abc> queryABCD(@Param("id") int id,@Param("from") int from,@Param("size") int size);
<select id="queryABCD" resultType="abc">
		select * from T_aaaa s where id = #{id}
		limit #{from},#{size}
</select>

# 使用 where 元素,條件語句中判斷相等使用 ‘==’ 雙等於號,!使用單個 ‘=’ 等於號爲賦值操作!
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>
2. mybatis使用中 ‘#{ }’ 與 ‘${ }’ 的區別
字符串替換

默認情況下,使用 #{} 格式的語法會導致 MyBatis 創建 PreparedStatement 參數佔位符並安全地設置參數(就像使用 ? 一樣)。 這樣做更安全,更迅速,通常也是首選做法,不過有時你就是想直接在 SQL 語句中插入一個不轉義的字符串。 比如,像 ORDER BY,你可以這樣來使用:

ORDER BY ${columnName}

這裏 MyBatis 不會修改或轉義字符串。

當 SQL 語句中的元數據(如表名或列名)是動態生成的時候,字符串替換將會非常有用。 舉個例子,如果你想通過任何一列從表中 select 數據時,不需要像下面這樣寫:

@Select("select * from user where id = #{id}")
User findById(@Param("id") long id);

@Select("select * from user where name = #{name}")
User findByName(@Param("name") String name);

@Select("select * from user where email = #{email}")
User findByEmail(@Param("email") String email);

// and more "findByXxx" method

可以只寫這樣一個方法:

@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);

其中 ${column} 會被直接替換,而 #{value} 會被使用 ? 預處理。 因此你就可以像下面這樣來達到上述功能:

User userOfId1 = userMapper.findByColumn("id", 1L);
User userOfNameKid = userMapper.findByColumn("name", "kid");
User userOfEmail = userMapper.findByColumn("email", "[email protected]");

這個想法也同樣適用於用來替換表名的情況。

提示 用這種方式接受用戶的輸入,並將其用於語句中的參數是不安全的,會導致潛在的 SQL 注入攻擊,因此要麼不允許用戶輸入這些字段,要麼自行轉義並檢驗。 
3. 基本使用(官網中文截圖)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章