SpringBoot简单集成Mybatis

in 笔记 with 0 comment

引入Mybatis的starter依赖

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.1</version>
</dependency>

编写Entity

@Entity
@DynamicUpdate
@Data
public class ProductCategory {

    /** 类目id. */
    @Id
    @GeneratedValue
    private Integer categoryId;

    /** 类目名字. */
    private String categoryName;

    /** 类目编号. */
    private Integer categoryType;

    private Date createTime;

    private Date updateTime;

    public ProductCategory() {
    }
}

基于注解的方式

在接口上用注解编写SQL

public interface ProductCategoryMapper {

    @Insert("insert into product_category(category_name, category_type) values (#{categoryName, jdbcType=VARCHAR}, #{category_type, jdbcType=INTEGER})")
    int insertByMap(Map<String, Object> map);

    @Insert("insert into product_category(category_name, category_type) values (#{categoryName, jdbcType=VARCHAR}, #{categoryType, jdbcType=INTEGER})")
    int insertByObject(ProductCategory productCategory);

    @Select("select * from product_category where category_type = #{categoryType}")
    @Results({
            @Result(column = "category_id", property = "categoryId"),
            @Result(column = "category_name", property = "categoryName"),
            @Result(column = "category_type", property = "categoryType")
    })
    ProductCategory findByCategoryType(Integer categoryType);

    @Select("select * from product_category where category_name = #{categoryName}")
    @Results({
            @Result(column = "category_id", property = "categoryId"),
            @Result(column = "category_name", property = "categoryName"),
            @Result(column = "category_type", property = "categoryType")
    })
    List<ProductCategory> findByCategoryName(String categoryName);

    @Update("update product_category set category_name = #{categoryName} where category_type = #{categoryType}")
    int updateByCategoryType(@Param("categoryName") String categoryName,
                             @Param("categoryType") Integer categoryType);

    @Update("update product_category set category_name = #{categoryName} where category_type = #{categoryType}")
    int updateByObject(ProductCategory productCategory);

    @Delete("delete from product_category where category_type = #{categoryType}")
    int deleteByCategoryType(Integer categoryType);

    ProductCategory selectByCategoryType(Integer categoryType);
}

基于xml方式

1.编写mapper接口
2.在resource目录下新建mapper包编写对应类的xml文件
CC711DF1F175458B95499297E597A8EC.png

<?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.imooc.dataobject.mapper.ProductCategoryMapper" >

    <resultMap id="BaseResultMap" type="com.imooc.dataobject.ProductCategory">
        <id column="category_id" property="categoryId" jdbcType="INTEGER" />
        <id column="category_name" property="categoryName" jdbcType="VARCHAR" />
        <id column="category_type" property="categoryType" jdbcType="INTEGER" />
    </resultMap>

    <select id="selectByCategoryType" resultMap="BaseResultMap" parameterType="java.lang.Integer">
        select category_id, category_name, category_type
        from product_category
        where category_type = #{category_type, jdbcType=INTEGER}
    </select>
</mapper>

加入到spring容器

在SpringBoot程序入口加上@MapperScan注解扫描mapper接口所在路径

@SpringBootApplication
@MapperScan(basePackages = "com.imooc.dataobject.mapper")
@EnableCaching
public class SellApplication {

   public static void main(String[] args) {
      SpringApplication.run(SellApplication.class, args);
   }
}

在application配置文件中加入xml文件所在路径(注解方式可省略)

mybatis:
  mapper-locations: classpath:mapper/*.xml

总结-注意事项

1.使用注解方式时,如果入参个数大于两个必须使用@Param注解

@Update("update product_category set category_name = #{categoryName} where category_type = #{categoryType}")
int updateByCategoryType(@Param("categoryName") String categoryName,
                         @Param("categoryType") Integer categoryType);

2.当参数大于两个时,入参可以选择Map也可以选择Object,但注意sql写法要加上jdbcType

@Insert("insert into product_category(category_name, category_type) values (#{categoryName, jdbcType=VARCHAR}, #{category_type, jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);

@Insert("insert into product_category(category_name, category_type) values (#{categoryName, jdbcType=VARCHAR}, #{categoryType, jdbcType=INTEGER})")
int insertByObject(ProductCategory productCategory);

3.当使用查询方法时,返回多条数据,返回类型要使用集合类型,否则报错(JPA会返回第一条数据,Mybatis在这里相比更严禁)

@Select("select * from product_category where category_name = #{categoryName}")
@Results({
        @Result(column = "category_id", property = "categoryId"),
        @Result(column = "category_name", property = "categoryName"),
        @Result(column = "category_type", property = "categoryType")
})
List<ProductCategory> findByCategoryName(String categoryName);

4.建议在开发环境在mapper层配置好sql的log

logging:
  level:
    com.imooc.dataobject.mapper: trace