SpringBoot(三)SpringBoot整合MyBatis

Spring框架常用注解简单介绍
SpringMVC常用注解简单介绍
SpringBoot(一)创建一个简单的SpringBoot工程
SpringBoot(二)SpringBoot多环境配置
SpringBoot(三)SpringBoot整合MyBatis
SpringBoot(四)SpringBoot整合 Redis

MyBatis是什么?

MyBatis是一个持久层框架,是 apache 下的一个顶级项目。MyBatis让程序员将主要精力放在 sql 上,通过MyBatis提供的映射方式,自由灵活生成满足需求的 sql 语句。
MyBatis可以向 PreparedStatement中的输入参数自动进行输入映射,将查询结果集灵活映射成 Java对象(输出映射)。

MyBatis使用步骤:
  1. 在pom.xml文件中配置MyBatis依赖:

    org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.1 mysql mysql-connector-java 8.0.16
  2. 修改application.properties文件,配置数据库(一般我们会在对应环境的配置文件中,配置不同的数据库)

    配置MyBatis的Mapper.xml文件所在路径

    mybatis.mapper-locations=mappers/*.xml

    #DB Configuration:
    spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/bookstore
    spring.datasource.username=root
    spring.datasource.password=12345678

数据库建表语句
首先我们在本地安装MySQL数据库,然后执行下面的SQL:

CREATE TABLE `book` (
  `bid` char(32) NOT NULL AUTO_INCREMENT,
  `bname` varchar(100) NOT NULL,
  `price` decimal(5,1) DEFAULT NULL,
  `author` varchar(100) DEFAULT NULL,
  `image` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`bid`),
  KEY `cid` (`cid`)
)

INSERT INTO `book`(`bname`, `price`, `author`, `image`) VALUES ('C语言从入门到精通 精粹版', 39.6, '梁义涛 /2018-08-01 /人民邮电出版社', 'book_img/C.jpg');
  1. 创建Mapper文件



    ProductMapper

    @Mapper
    public interface ProductMapper {

     Product selectById(String id);
    

    }

  2. 创建Mapper对应的xml文件



    WX20200520-183447.png

    <?xml version="1.0" encoding="UTF-8" ?> select bid, bname, price, author, image from book where bid = #{id}
  3. 修改service改成从Mapper访问数据库

    @Service(“iProductService”)
    public class ProductServiceImpl implements IProductService {

     @Autowired
     ProductDao productDao;
    
     @Autowired
     private ProductMapper productMapper;
    
     @Override
     public Product getProductById(String id) {
    

    // return productDao.getProductById(id);

         // 改成mybatis从数据库获取数据
         return productMapper.selectById(id);
     }
    

    }

启动工程,然后打开打开浏览器输入:http://localhost:8081/springbootdemo/product/1

返回:
{
“bid”: “1”,
“bname”: “C语言从入门到精通 精粹版”,
“price”: 39.6,
“author”: “梁义涛 /2018-08-01 /人民邮电出版社”,
“image”: “book_img/C.jpg”
}
最后编辑于:2024-08-25 10:33:29
© 著作权归作者所有,转载或内容合作请联系作者

喜欢的朋友记得点赞、收藏、关注哦!!!

  • 18
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值