Springboot + Mybatis

SpringBoot整合MyBatis实战
本文介绍如何在SpringBoot项目中整合MyBatis,包括添加依赖、配置Mapper扫描、编写XML映射文件及实现增删改查操作。具体步骤涉及配置依赖、使用@MapperScan注解、创建Mapper XML文件、定义Mapper接口以及实现Controller层。

Springboot + Mybatis

并没有使用注解的形式

之后看项目要求怎么写吧


1/添加依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- Oracle的jdbc驱动包 -->
<dependency>
    <groupId>oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.4</version>
</dependency>

2/在Springboot启动方法上添加@MapperScan注解

通过@MapperScan注解可以指定要扫描的Mapper类的包的路径,或者在Mapper接口上使用@Mapper注解也可以达到同样的效果

@SpringBootApplication
@MapperScan("com.mybatis.springbootmybatis.mapper")
public class SpringbootMybatisApplication {

3/Mapper.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.mybatis.springbootmybatis.mapper.UserInfoMapper">
    <select id="count" resultType="int">
        select count(*) from emp
    </select>    
<!--
  记得有起别名的注解,没找到 returnType先写全名  
-->
<select id="selectEmpNameById" resultType="com.mybatis.springbootmybatis.domain.UserInfo" parameterType="String"> select FROM EMp Where Empno = #{id} </select></mapper>

4/Mapper 接口

public interface UserInfoMapper {
    int count();
    UserInfo selectEmpNameById(String id);
}

5/service 和 serviceImpl 略

6/Controller

@RestController
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping(value="/count",method={RequestMethod.POST,RequestMethod.GET})
    public String getConut(){
       System.out.println(userInfoService.count());
       return  "aa"  + userInfoService.count();
    }
    @RequestMapping(value="/getEmpById" ,method = {RequestMethod.GET,RequestMethod.POST})
    public UserInfo getEmpNameById(@Param("id") String id){
        return userInfoService.getEmpNameById(id);
    }
}

7/application.properties

#mybatis.mapper-locations=*/mapper/*.xml
mybatis mapper 文件的区域
mybatis.mapper-locations=classpath:mapper/*.xml






























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值