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