使用SpringBoot整合Mybatis的两种方式

第一种:常规的整合方式(以Mysql为例)

先上我的文件目录,因为展示以整合为主,因此在这里没有严格按照controller-service-mapper分层
在这里插入图片描述

第一步、导入相关依赖:

<!--导入mybatis整合包-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
<!--导入lombok,非必要-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
<!--导入jdbc包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
<!--导入web相关依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--导入mysql链接器-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

第二步、编写yml文件配置数据源以及相关配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: ******
    password: ******
    driver-class-name: com.mysql.cj.jdbc.Driver

# 整合Mybatis
mybatis:
  # 配置包别名
  type-aliases-package: com.gdpu.pojo
  # 配置映射路径
  mapper-locations: classpath:mapper/*.xml

第三步、编写pojo类
这里的pojo类以大家的需求为主,我这里仅简单的展示,使用了Lombok进行了简化

@Data//get,set方法
@NoArgsConstructor//无参构造
@AllArgsConstructor//有参构造
public class account {
    public Integer id;
    public String name;
    public Double money;
}

第四步、根据需求编写mapper接口

@Repository
public interface AccountMapper {

    //增
    int addAccount(account account);

    //删
    int deleteAccountByID(Integer id);

    //改
    int updateAccountByID(account account);

    //查所有
    List<account> queryAccount();

    //根据ID查询
    account queryAccountByID(Integer id);

}

第五步、在启动类开启mapper的注解扫描

@SpringBootApplication
@MapperScan("com.gdpu.mapper")
public class Springboot05MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot05MybatisApplication.class, args);
    }
}

第六步、配置映射文件xml,引入约束空间,编写sql语句。此处我在resources下新建了mapper文件夹存放mapper.xml文件。值得注意的是,如果没有配置别名,resultType,paramType应写类的全限定类名。useCache表示开启缓存。namespace记得写对应接口的全路径

<?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.gdpu.mapper.AccountMapper">
    <select id="queryAccount" resultType="account" useCache="true">
    select * from account
   </select>

    <select id="queryAccountByID" resultType="account" useCache="true">
    select * from account where id = #{id}
   </select>

    <insert id="addAccount" parameterType="account">
        insert into account (name,money) values(#{name},#{money})
    </insert>

    <update id="updateAccountByID" parameterType="account">
        update account set name=#{name},money=#{money} where id=#{id}
    </update>

    <delete id="deleteAccountByID" parameterType="Int">
        delete from account where id=#{id}
    </delete>
</mapper>

第七步、编写Controller方法,实现业务逻辑

@RestController
public class UserController {
	//注入mapper接口
    @Autowired
    public AccountMapper accountMapper;

    //查询所有
    @GetMapping("queryAccount")
    public List<account> queryAccount(){
        List<account> accounts = accountMapper.queryAccount();
        for (account account : accounts) {
            System.out.println(account);
        }
        return accounts;
    }
    //添加用户
    @GetMapping("addAccount")
    public String addAccount(){
        account account = new account();
        account.setMoney(1000.0);
        account.setName("mybatis整合");
        accountMapper.addAccount(account);
        return "add ok";
    }
    //删除用户
    @GetMapping("deleteAccount/{id}")
    public String deleteAccount(@PathVariable("id") Integer id){
        accountMapper.deleteAccountByID(id);
        return "delete ok";
    }

    //修改用户
    @GetMapping("updateAccountByID")
    public String updateAccountByID(){
        accountMapper.updateAccountByID(new account(2,"mybatis更新",998.1));
        return "修改成功";
    }

    @GetMapping("queryAccountByID/{id}")
    public account queryAccountByID(@PathVariable("id") Integer id){
         account account = accountMapper.queryAccountByID(id);
         return account;
    }
}

第二种、使用通用Mapper整合

第一步、依然不变的是引入jar包,除了上面所讲的jar包以外,在原有的基础上引入一个新的jar包通用mapper

 <dependency>
     <groupId>tk.mybatis</groupId>
     <artifactId>mapper-spring-boot-starter</artifactId>
</dependency>

第二步、编写接口Mapper继承Mapper,Mapper<>尖括号里面的泛型填写自己对应的类,例如我的pojo类是account,在这里我就写account;在这里不需要写对应的方法,只需要继承通用Mapper即可,如果mapper里面的方法不能满足我们的业务需求,也可以在这里编写sql代码

public interface AccountMapper extends Mapper<account> {
}

第三步、编写pojo类,与数据库表中的主键,表名对应

@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name="account)
public class account {
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer id;
    public String name;
    public Double money;
}

第四步、同理,开启Mapper的注解扫描以及别名扫描

启动类:

@SpringBootApplication
@MapperScan("com.gdpu.mapper")//扫描该包下的所有注解
public class Springboot05MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot05MybatisApplication.class, args);
    }

}

yml文件:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: *******
    password: *******
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  type-aliases-package: com.yimai.item.pojo #别名扫描```

第五步、编写Controller,在Controller注入对应的Mapper

@RestController
public class UserController {
    @Autowired
    public AccountMapper accountMapper;

    //如根据id查找对应的account
    @GetMapping("queryAccountByID/{id}")
    public account queryAccountByID(@PathVariable("id") Integer id) {
    	//调用通用Mapper里面的方法,免去了手动写sql语句的麻烦
        return this.accountMapper.selectByPrimaryKey(id);
    }
}

至此,通用Mapper的方式也整合完啦!对比两种整合方式,使用通用Mapper的整合方式,可以更好的缩短代码,完成对应的逻辑功能,并且省去了编写mapper.xml映射文件以及编写对应sql语句的麻烦,常用的通用Mapper的方法如下:
通用 Mapper常用方法,转载自大鹏小站

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值