SpringBoot之使用注解方式整合MyBatis

本文介绍了如何使用注解方式整合MyBatis,包括创建Mapper接口并定义SQL操作,如查询、添加、修改和删除方法。同时,针对可能出现的值为null问题,提出了在全局配置文件中启用驼峰命名匹配的解决方案,确保字段名和Model层变量的对应。
摘要由CSDN通过智能技术生成

一、使用注解方式整合MyBatis

1、创建Mapper接口文件:@Mapper

(1)创建一个包(mapper)

(2)在包里创建mapper接口文件

例如:创建CommentMapper接口文件

@Mapper  //表示该类是一个mybatis接口文件,是需要被springboot进行扫描的。
public interface CommentMapper{

    //查询方法
    @Select("select * from t_comment where id = #{id}")
    public Comment findById(Integer id);

    //添加方法
    @Insert("insert into  t_comment values(#{id},#{content},#{author},#{aId})")
    public void insertComment(Comment comment);

    //修改方法
    @Update("update t_comment set content=#{content} where id = #{id}")
    public void updateComment(Comment comment);

    //删除方法
    @Delete("delete from t_comment where id = #{id}")
    public void deleteComment(Integer id);
}

2、编写测试类方法进行接口方法测试及整合测试

例如:

@Autowired
private CommentMapper commentMapper;

@Test
public void contextLoads(){
    Comment comment = commentMapper.findById(1);
    System.out.println(comment);

}

3、出现问题

如果出现值为null的情况,可能是因为数据库字段名和model层变量名对应不上,可以在全局配置文件中添加一个驼峰命名匹配的设置。

//在全局配置文件中开启驼峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熊凯瑞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值