SpringBoot中配置mybatis

①pom.xml中引入

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

②resources下创建以下文件

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>

AccountMapper.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">
#这边的包路径和sql语句需要根据自身的表的写
<mapper namespace="com.atubo.admin.mapper.AccountMapper">

        <select id="getAccount" resultType="com.atubo.admin.bean.Account">
            select * from user where userName=#{userName}
        </select>
</mapper>

③编写Mapper接口

 

@Mapper
public interface AccountMapper {
    public Account getAccount(String userName);
}

④编写sql映射mapper接口

<mapper namespace="com.atubo.admin.mapper.AccountMapper">

        <select id="getAccount" resultType="com.atubo.admin.bean.Account">
            select * from user where userName=#{userName}
        </select>
</mapper>

⑤application.yaml中配置mybatis规则

#配置mybatis规则
mybatis:
#  全局配置的文件位置
#  config-location: classpath:mybatis/mybatis-config.xml
#  映射路径
  mapper-locations: classpath:mybatis/mapper/*.xml
#  可以不写配置文件路径 写下面这个 但是上面的全局配置文件和下面这个不能同时存在 否则SpringBoot 不知道解析哪一个
  configuration: #指定mybatis全局配置文件中的配置项
    map-underscore-to-camel-case: true

接下去是使用:

@Service
public class AccountService {

    @Autowired
    AccountMapper accountMapper;

    public Account getAccountByuserName(String userName){
        return accountMapper.getAccount(userName);
    }
}

@Data
public class Account {

    private String userName;
    private String password;
}

@Autowired
AccountService accountService;

@ResponseBody
@GetMapping("/acct")
public Account getByuserName(@RequestParam("userName") String userName){

    return accountService.getAccountByuserName(userName);
}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值