springboot整合mybatis

1. 创建项目

加入相关依赖

2. 定义数据源

在配置文件中设置使用数据库的相关配置

spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/ssm_db
        username: root
        password: dem

3. 创建pojo层

POJO的格式是用于数据的临时传递,它只能装载数据,作为数据存储的载体,而不具有业务逻辑处理的能力。

属性类型和名称应与数据库的数据相对应

package com.example.domain;

public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Book{" +
        "id=" + id +
        ", type='" + type + '\'' +
        ", name='" + name + '\'' +
        ", description='" + description + '\'' +
        '}';
    }
}

4. 编写dao

注解版

用 @Mapper 注解标识,我们使用#{id}来标识参数。@Mapper 注解把 mapper 这个 DAO 交给 Spring 管理,不再写 mapper 映射文件。

@Mapper
public interface BookDao {

    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);
}

xml配置文件版

5. 编写service

需要在实现类中使用 @Service 注解,才能被 SpringBoot 扫描,在 Controller 中使用 @Autowired 注入

在 service 目录中新建 Book类

@Service
public class BookService {
    @Autowired
    private BookDao bookDao;

    public Book getById(Integer id){
        return bookDao.getById(id);
    }
}

6. 编写Controller

使用Restful 风格,直接返回数据。

@RestController
public class UserController {

    @Autowired
    private BookService;

    @GetMapping("/getById")
    public User getUser(@RequestParam("id") Integer id){
        return BookService.getById(id);
    }
   
}

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值