SpringBoot使用MyBatis-注解版

in 笔记 with 0 comment

写XML是不可能了,这辈子都不可能了,只能靠注解才能维持生活的样子

数据库

CREATE TABLE `books` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `bookname` varchar(50) NOT NULL DEFAULT '',
  `b_price` varchar(10) NOT NULL DEFAULT '',
  `image` varchar(100) DEFAULT NULL,
  `stock` int(10) DEFAULT NULL COMMENT '库存',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='书';

INSERT INTO `books` VALUES (1,'java','10','https://xx.com/xx.jpg',12);

添加依赖

<dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>1.3.2</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
    </dependency>

在application.properties中配置mysql的连接配置

spring.datasource.url=jdbc:mysql://localhost:3306/shop
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

创建实体类

public class Books{
    private Integer id;
    private String bookName;
    private String bPrice;
    private String image;
    private Integer stock;
    
    /**
    get set toString
    */
}

创建books对应的mapper

@Mapper
public interface BooksMapper {

 @Results({
            //返回参数绑定
            @Result(property = "bPrice",column = "b_price")
    })
    @Select("select * from books where bookname = #{name}")
    Books findByBookName(@Param("name") String name);
}

单元测试走起

不写xml的感觉真好 :trollface: :trollface:

Responses