springboot-整合mybatis-配置文件法-08

本文介绍了如何将Spring Boot与MyBatis进行整合,包括引入依赖、定义Mapper接口、编写Mapper XML文件、配置全局设置以及实现服务层。通过这些步骤,你可以快速地搭建起一个Spring Boot集成MyBatis的数据访问层。
摘要由CSDN通过智能技术生成

1.导入依赖

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

2.编写com.atguigu.admin.mapper.AccountMapper接口

package com.atguigu.admin.mapper;

import com.atguigu.admin.bean.Account;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AccountMapper {

    public Account getAccount(Long id);
}

3.注册mapper对应的serivce:com.atguigu.admin.service.AccountService

package com.atguigu.admin.service;

import com.atguigu.admin.bean.Account;
import com.atguigu.admin.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountService {
    @Autowired
    AccountMapper accountMapper;

    public Account getAccount(Long id) {
        return accountMapper.getAccount(id);
    }
}

4.编写sql文件mybatis/mapper/AccountMapper.xml绑定接口

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.admin.mapper.AccountMapper">
<!--public Account getAccount(Long id);-->
    <select id="getAccount" resultType="com.atguigu.admin.bean.Account">
        select  * from account_tbl where id = #{id}
    </select>
</mapper>

5.在全局配置文件application.yml中,指定mapper配置文件的位置,以及全局配置文件信息

mybatis:
#  要么就在config-location中写明位置,用mybatis配置文件的形式来配置,要么就用springboot全局配置,二者不能同时存在
#  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值