SpringBoot之MyBatis整合

一种基于注解一种基于配置文件

一. 基于注解

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值