1. mybatis的依赖引入
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
2. 启动类中@MapperScan的注解
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.***.dataObject.mapper")
public class SellApplication {
public static void main(String[] args) {
SpringApplication.run(***Application.class, args);
}
}
3. 在mapper接口中写上方法
3.1 注解方式——sql直接写在注解后
public interface ProductCategoryMapper {
@Insert("insert into product_category(category_name, category_type) values (#{category_name, jdbcType=VARCHAR}, #{category_type, jdbcType=INTEGER})")
int insertByMapper(Map<String, Object> map);
}
3.2 xml方式(mybatis官方并不推崇这种写法)
3.2.1 定义方法
public interface ProductCategoryMapper {
ProductCategory selectByCategoryType(Integer categoryType);
}
3.2.2 在xml文件中写上sql
<?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.***.dataObject.mapper.ProductCategoryMapper" >
<!--type对应实体类-->
<resultMap id="BaseResultMap" type="com.***.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>
<!--id对应接口 com.***.dataObject.mapper.ProductCategoryMapper 中的 selectByCategoryType 方法名-->
<select id="selectByCategoryType" resultMap="BaseResultMap" parameterMap="java.lang.Integer">
SELECT CATEGORY_ID, CATEGORY_ID, CATEGORY_ID
FROM PRODUCT_CATEGORY
WHERE CATEGORY_TYPE = #{CATEGORY_TYPE, JDBCTYPE=INTEGER}
</select>
</mapper>
3.2.3 在.yml(或.properties)文件配置xml的位置
#定位xml形式的mapper路径
mybatis:
mapper-locations: calsspath:mapper/*.xml