1. 程式人生 > >Mybatis框架--基礎使用的一些坑

Mybatis框架--基礎使用的一些坑

settings () ash string mysql select tty tin {0}

1 mybatis的底層實現

  使用dom4j將配置文件讀取出來,使用動態代理動態創建代理對象,中間的調用方法和過程是使用java的反射機制

2 數據庫字段和屬性名不一致的問題 

1 在查詢語句中使用別名
  
  <select id="selectBlog2" parameterType="int" resultType="Blog">
select
`id`,
`title`,
`author_id` as authorId,
`state`,
`featured`,
`style`
from
blog where id = #{id}
  </select>

2 使用ResultMap

<resultMap type="Blog" id="blogResultMap
">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="author_id" property="authorId" jdbcType="INTEGER" />
</resultMap>
  
   <select id="selectBlog3" parameterType="int" resultMap="blogResultMap">
select * from blog where id = #{id}
</select>

3 排序時接受參數的字符選擇問題

 如果使用#,那麽sql不會報錯,但是排序功能不能使用;所以應該使用$(參數是表名或是列名)
中文排序,需要使用mysql的轉換函數 CONVERT()

<select id="selectBySort" parameterType="string" resultMap="blogResultMap">
select * from blog order by CONVERT(${value} USING GBK)
</select>

4 傳遞多參數的方法

1 使用索引,按照參數的位置從0開始
  
  <select id="selectByPage" resultMap="blogResultMap">
select * from blog limit
#{0}, #{1}
</select>

2 使用接口註解,註意占位參數的名字要和註解參數的名字一致


  List<Blog> selectByPage2(
@Param(value="offset") int offset,
@Param(value="pagesize") int pagesize);

  <select id="selectByPage2" resultMap="blogResultMap">
select * from blog limit
#{offset}, #{pagesize}
</select>

3 使用map傳參,註意占位參數的名字要和map中的key一一對應

   Map<String, Object> map = new HashMap<String, Object>();
map.put("offset", 2);
map.put("pagesize", 2);

List<Blog> blogList = blogMapper.selectByPage3(map);

   <select id="selectByPage3" resultMap="blogResultMap">
select * from blog limit
#{offset}, #{pagesize}
</select>

  

5 獲取剛剛插入數據的id(帶有自增主鍵)

1 配置屬性useGeneratedKeys="true" keyProperty="id"

  <insert id="insertBlog" parameterType="Blog" useGeneratedKeys="true" keyProperty="id">

2 在全局配置文件中配置settings選項,並且在mapper的insert節點配置屬性keyProperty="id"

  <!-- 自增主鍵 -->
<settings>
<setting name="useGeneratedKeys" value="true" />
</settings>

  <insert id="insertBlog2" parameterType="Blog" keyProperty="id">

3 直接查詢

<insert id="insertBlogMySql">
<selectKey resultType="java.lang.Integer" order="AFTER"
keyProperty="id">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>

4 沒有自增主鍵的數據庫查詢(oracle)

  <insert id="insertBlogOracle">
<selectKey resultType="java.lang.Integer" order="BEFORE"
keyProperty="id">
select seq.nextval as id from dual
</selectKey>
</insert>

Mybatis框架--基礎使用的一些坑