一种基于注解一种基于配置文件
一. 基于注解
1. 导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
2. 写一个接口, 直接写SQL
@Mapper
public interface UseryMapper {
@Insert("insert into table(name, type) value (#{name, jdbcType=INTEGER}, #{type, jdbcType=VARCHAR})")
int insertByMap(Map<String, Object> map);
@Insert("insert into table(name, type) value (#{name, jdbcType=INTEGER}, #{type, jdbcType=VARCHAR})")
int insertByObject(User user);
@Select("select * from table where type = #{type}")
@Results({
@Result(column = "type", property = "type"),
@Result(column = "id", property = "id"),
@Result(column = "name", property = "name")
})
User findByCategoryType(Integer tpye); // type为主键
@Select("select * from table where name = #{name}")
@Results({
@Result(column = "type", property = "type"),
@Result(column = "id", property = "id"),
@Result(column = "name", property = "name")
})
List<User> findByName(String name); // 查询结果可能有多条
// 更新时候 如果传入多个参数必须加@Param注解指定传入的值
@Update("update table set name = #{name} where type = #{type}")
int updateByType(@Param("name") String name, @Param("type") Integer type);
// 传入一个对象
@Update("update table set name = #{name} where type = #{type }")
int updateByObject(User user);
@Delete("delete from table where type = #{type}")
int deleteByType(Integer type);
}
其实查询时候可以不写包含@Results在内的所有注解, 但是需要在每一个入参中使用@Param指定参数
@Mapper注解不需要在每一个Mapper里面都写, 只需要在启动类头加上注解即可
@MapperScan(basePackages = "com.mapper")
二. 依赖xml配置文件
1. 跟传统的一样, 需要声明一个接口和一个xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper SYSTEM "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.imooc.dataobject.mapper.ProductCategoryMapper">
<resultMap id="BaseResultMap" type="com.User">
<id column="id" property="id" jdbcType="INTEGER"></id>
<id column="type" property="type" jdbcType="INTEGER"></id>
<id column="name" property="name" jdbcType="VARCHAR"></id>
</resultMap>
<select id="selectByCName" resultMap="BaseResultMap" parameterType="java.lang.Integer">
select * from table where name = #{name, jdbcType=INTEGER}
</select>
</mapper>
2. yml增加配置路径
mybatis:
config-location: classpath:mapper/*.xml