SpringBoot Mybatis配置文件版使用

本文详细介绍了使用MyBatis框架进行配置的方法,包括pom.xml依赖导入、Bean配置、Mapper接口定义、mybatis配置文件设置及sql执行文件编写,同时展示了如何通过yml文件指定配置路径,最终实现controller层对Mapper的调用。

摘要生成于 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、Mapper、mybatis配置文件及调用controller

配置存储数据的Bean:

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

Mapper:里面没有执行的sql,sql在配置文件中

@Mapper
public interface EmployeeMapper {

    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);
}

mybatis配置文件:包含两个配置文件,一个是mybatis-config.xml用来配置mybatis的一些设置;另一个是执行的sql文件,可以是多个 xx.xml
mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

执行sql的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.jdbctest.springbootdatamybatis.mapper.EmployeeMapper">
    <select id="getEmpById" resultType="com.jdbctest.springbootdatamybatis.bean.Employee">
        SELECT * FROM employee where id=#{id}
    </select>

    <insert id="insertEmp">
        INSERT into employee(id,lastname,email,gender,d_id) values (#{id},#{lastname},#{email},#{gender},#{dId})
    </insert>
</mapper>

配置yml文件,告知mybatis配置文件在哪:

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

最后controller调用mapper即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值