一、使用注解方式整合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