SpringBoot整合Mybatis

我们引入上一章节的Druid配置文件,并且建立两张表,如下所示:
在这里插入图片描述
在这里插入图片描述
当然,我们也可以写一个sql文件,再用深入理解springboot(5)的方法,也能得到同样的结果。

我们建立两个bean——>Department and Employee

public class Department {

    private Integer d_id;
    private String d_name;

   ....省去get/set
}

public class Employee {
    private Integer id;
    private String lastname;
    private String email;
    private Integer gender;
    private Integer d_id;

    ....省去get/set
}

然后建立一个mapper.DepartmentMapper

@Mapper
public interface DepartmentMapper {
    @Select("select * from department where d_id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where d_id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "d_id")//告诉注解版的mybatis【department】对象中的id为自增主键
    @Insert("insert into department(d_id, d_name) values(#{d_id},#{d_name})")
    public int insertDept(Department department);

    @Update("update department set d_name=#{d_name} where d_id=#{d_id}")
    public int updateDept(Department department);
}

最后,再安排一个Controller.DeptController

@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/dept")
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;
    }
}

当然,为了方便起见(其实也没方便什么!!),我们可以去掉@Mapper ,用一个@MapperScan加到启动类上面,相当于指定给 mapper包下面的所有的类都加上@Mapper一样,批量扫描所有的接口:

@MapperScan(value = "com.king.mybatis.mapper")
@SpringBootApplication
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

附赠数据源一些配置文件:

spring:
  datasource:
    username: root  # 数据库账号密码
    password: 123456
    url: jdbc:mysql://192.168.195.130:3306/jwt?serverTimezone=UTC  # 改成自己的数据库
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

还有XML配置的方法,这个之前学过,就不再赘述。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值