springboot2.0与mybatis整合

本文介绍如何在SpringBoot项目中集成MyBatis,包括使用依赖包mybatis-spring-boot-starter,通过注解和配置文件两种方式实现数据访问层的开发。详细解释了@Mapper注解的使用及XML配置的指定。

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

    mybatis为了自动适配springboot开发适配包,需要引入

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis‐spring‐boot‐starter</artifactId>
    <version>2.1.2</version>
</dependency>

可以使用2种方式整合

一、注解方式,直接在dao上注解

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

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

    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

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

备注:需要加入@Mapper才能被扫描到或者在全局(SpringbootmybatisApplication)上进行配置@MapperScan(value = "com.cax.springboot.mapper")

二、使用配置文件方式

使用该方式实现需要指定xml实现文件

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
@Mapper
public interface EmployeeMapper {

    public Employee getEmployeeById(Integer id);
    
}

xml文件内容如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cax.springboot.mapper.EmployeeMapper">
    <select id="getEmployeeById" parameterType="Integer" resultType="com.cax.springboot.entry.Employee">
        select * from employee where id = #{id}
    </select>
</mapper>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值