1. 程式人生 > 實用技巧 >mybatis 最佳實戰

mybatis 最佳實戰

mybatis 最佳實戰

目錄

1. mybatis 使用步驟

  1. 環境搭建,依賴匯入,配置檔案

  2. mybatis generater 生成檔案

  3. 修改實體類(不可刪除,但是可以新增)

  4. dao 層新增mapper 多表連線查詢的方法;

  5. Xml 檔案配置SQL 語句,新增對映實體類

2. 依賴匯入

 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
</dependency>
<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
 </dependency>

3. 配置檔案

spring:
  datasource:
    url: jdbc:mysql://49.233.186.242:3389/shop?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:generator/*.xml
logging:
  level:
    com.yangtao.demo: debug

4. 一對多對映檔案 (對映裡面有引用類)

  <resultMap id="BaseResultMap4" type="com.yangtao.demo.model.TbOrder">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="CODE" jdbcType="VARCHAR" property="code" />
    <result column="total" jdbcType="DOUBLE" property="total" />
    <result column="user_id" jdbcType="INTEGER" property="userId" />
    <association property="tbUser" javaType="com.yangtao.demo.model.TbUser">
      <id column="id" jdbcType="INTEGER" property="id" />
      <result column="username" jdbcType="VARCHAR" property="username" />
      <result column="loginname" jdbcType="VARCHAR" property="loginname" />
      <result column="PASSWORD" jdbcType="VARCHAR" property="password" />
      <result column="phone" jdbcType="VARCHAR" property="phone" />
      <result column="address" jdbcType="VARCHAR" property="address" />
    </association>
  </resultMap>
<select id="selectCodeByUid" parameterType="java.lang.Integer" resultMap="BaseResultMap2">
  select o.CODE,o.total from tb_user u,tb_order o
  where u.id=o.user_id and u.id=#{uid}
</select>

5. 一對多對映檔案 (對映裡面有列表型別)

  <resultMap id="BaseResultMap3" type="com.yangtao.demo.dto.CodeTestDto">
    <result column="CODE" jdbcType="VARCHAR" property="code" />
    <result column="total" jdbcType="DOUBLE" property="total" />
    <collection property="codeTestDto" javaType="ArrayList"
                column="id" ofType="com.yangtao.demo.dto.CodeTestDto"                												select="com.yangtao.demo.dao.TbOrderDao.selectCodeByUidAndReturnList"
                fetchType="lazy">
      <result column="CODE"  property="code" />
      <result  column="total"  property="total"/>
    </collection>
  </resultMap>

6. CRUD 標籤

  <select id="selectCodeByUidAndReturnList2" parameterType="java.lang.Integer" resultMap="BaseResultMap4">
    select * from tb_user u,tb_order o
    where u.id=o.user_id and u.id=#{uid}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from tb_order
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.yangtao.demo.model.TbOrder" useGeneratedKeys="true">
    insert into tb_order (CODE, total, user_id)
    values (#{code,jdbcType=VARCHAR}, #{total,jdbcType=DOUBLE}, #{userId,jdbcType=INTEGER})
  </insert>
  <update id="updateByPrimaryKey" parameterType="com.yangtao.demo.model.TbOrder">
    update tb_order
    set CODE = #{code,jdbcType=VARCHAR},
      total = #{total,jdbcType=DOUBLE},
      user_id = #{userId,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>

7. 動態SQL

1.IF

 <select id="getBlogByConditionDynamic" resultMap="oneToManyNested">
        select t1.id blog_id, t1.title, t2.id post_id, t2.section
        from blog t1 left outer join post t2 on t1.id = t2.blog_id
        <where>
            <if test="title != null and title !=''">
                and t1.title like '%'||#{title}||'%'
            </if>
            <if test="section != null and section != ''">
                and t2.section like '%'||#{section}||'%'
            </if>
        </where>
    </select>
@Test
    public void testGetBlogByConditionDynamic() throws Exception {
        List<Blog> blogList = blogMapper.getBlogByConditionDynamic("", "section");
        Assert.assertNotNull(blogList);
    }
<select id="getBlogByTitleOrSection" resultMap="oneToManyNested">
        select t1.id blog_id, t1.title, t2.id post_id, t2.section
        from blog t1 left outer join post t2 on t1.id = t2.blog_id where 1=1
        <choose>
            <when test="title != null and title !=''">
                and t1.title like '%'||#{title}||'%'
            </when>
            <when test="section != null and section != ''">
                and t2.section like '%'||#{section}||'%'
            </when>
            <otherwise>
                and t1.title is not null and t2.section is not null
            </otherwise>
        </choose>
    </select>

3. trim

    <select id="getBlogByConditionDynamicTrim" resultMap="oneToManyNested">
        select t1.id blog_id, t1.title, t2.id post_id, t2.section
        from blog t1 left outer join post t2 on t1.id = t2.blog_id
        <trim prefix="where" prefixOverrides="and | or">
            <if test="title != null and title !=''">
                and t1.title like '%'||#{title}||'%'
            </if>
            <if test="section != null and section != ''">
                and t2.section like '%'||#{section}||'%'
            </if>
        </trim>
    </select>

4. set

    <update id="updateBlogTitleSet" parameterType="blog">
        update blog
        <set>
            <if test="title != null and title != ''">
                 title = #{title}
            </if>
            <if test="id != null and id != ''">
                , id = #{id}
            </if>
        </set>
        where id = #{id}
    </update>

5. foreach

	<select id="dynamicForeach2Test" resultType="Blog">
		select * from t_blog where id in
		<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
			#{item}
		</foreach>
	</select>

8. 引數傳遞

 List<Blog> getBlogByConditionDynamic(@Param("title") String title, @Param("section") String section);

9. 原理圖