SpringBoot Mybatis注解版使用

本文详细介绍了如何使用MyBatis注解版进行数据库操作,包括定义数据Bean、创建Mapper接口并使用注解配置SQL命令,以及实现CRUD操作。同时,讲解了如何配置controller与驼峰命名匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom.xml导入依赖:

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

Mybatis架构注解版组成:存放数据的Bean、执行sql命令的Mapper及调用controller

配置存储数据的Bean:

public class Department{
  private Integer id;
  private String name;
  ...
  getter&setter
  ...
}

灵魂
配置执行sql命令的Mapper:

//通过注解@Mapper指定这个是一个操作数据库的Mapper
@Mapper
public interface DepartmentMapper {
    //查
    @Select("select * from department where id=#{id}")
    public Department gerDeptById(Integer id);
    //删
    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);
    //增
    //下面这个注解是自增id
    //@Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(id,departmentname) values(#{id},#{departmentname})")
    public int insertDeptById(Department department);
    //改
    @Update("update department set id=#{id}, departmentname=#{departmentname} where id=#{id}")
    public int updateDeptById(Department department);
}

配置controller:

@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

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

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

如果想启动驼峰命名匹配需要在配置文件中添加:

mybatis:
  configuration:
    map-underscore-to-camel-case: true

可以通过在启动项添加注解对指定目录进行mapper扫描(文件下的mapper就不用再写注解@Mapper)

@MapperScan(value="com.jdbctest.springbootdatamybatis.mapper")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值