Spring Boot 使用Mybatis注解开发增删改查

使用逆向工程是遇到的错误

  • 错误描述
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.fei.mapper.VideoMapper.selectByExample
  • 解决办法

application.properties中增加如下配置

#============================#
#====== mybatis config ======#
#============================#
mybatis.type-aliases-package=com.fei.domain
mybatis.mapper-locations=classpath:mapper/*.xml

# open camel rule mapping
mybatis.configuration.map-underscore-to-camel-case=true
# show sql statement in console
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

使用Mybatis注解开发增删改查

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface VideoMapper {
    /**
     * 自己写的方法,使用// mapper接口扫描@MapperScan("com.fei.mapper")
     * 
     * @return
     */
    @Select("select * from video")
    @Results({
            // 结果集映射规则,自己编写接口方法时需要指定,若使用逆向工程自动生成的方法则不需要指定
            // column对应数据库表字段,property对应Java对象属性
            // 但是这种方法,假如数据库表字段很多会很麻烦,所以可以在application.properties配置文件中开启驼峰映射规则
            // mybatis.configuration.map-underscore-to-camel-case=true
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "cover_img", property = "coverImg"), @Result(column = "view_num", property = "viewNum") })
    List<Video> findAll();

    @Select("select * from video where id = #{id}")
    Video findById(int id);

    @Update("update video set title = #{title} where id = #{id}")
    int update(Video video);

    @Delete("delete from video where id = #{id}")
    int delete(int id);

    @Insert("insert into video (title, summary, cover_img, view_num, price, create_time, online, point) "
            + " values (#{title}, #{summary}, #{coverImg}, #{viewNum}, #{price}, #{createTime}, #{online}, #{point})")
    // 获取自增id
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int save(Video video);
}

猜你喜欢

转载自www.cnblogs.com/zxfei/p/11709994.html