Mybatis----面向接口

让mybatis自动生成dao层接口的实现类

这是dao层接口的实现类,在mybatis中我们可以省略这种实现接口的方式,直接面向接口操作数据库,mybatis可以帮我们自动生成接口的实现类,也就是下面这个实现类mybatis帮我们生成了。

1、修改service,生成代理对象,调用接口方法,等同于上述图片内容的作用。

复制代码
public class NewAccountService {
    SqlSession sqlSession= SqlSessionUtil.openSession();
    Account account=new Account();
    public void changeAccount(String from_number,String to_number,Double balance){
        //获取接口对象相当于AccountDao accountDao=new AccountDaoImpl();
        AccountDao mapper = sqlSession.getMapper(AccountDao.class);
        //判断余额是否充足
        Account account=new Account();
        if(mapper.select(from_number)<balance){
            System.out.println("余额不足");
        }
        else{

            account.setAccountNumber(from_number);
            account.setBalance(mapper.select(to_number)-balance);
            mapper.updata(account);
            account.setAccountNumber(to_number);
            account.setBalance(mapper.select(to_number)+balance);
            mapper.updata(account);
        }
        sqlSession.commit();
        sqlSession.close();
    }
}

2、修改映射文件,将映射文件中的namespace标签属性修改为Dao层接口所在的位置,将查询更新语句中的id修改该为与接口中对应的方法一致。

3、测试

初始数据库数据

结果

相关推荐
!if13 小时前
springboot mybatisplus 配置SQL日志,但是没有日志输出
spring boot·sql·mybatis
讓丄帝愛伱13 小时前
Mybatis Log Free插件使用
java·开发语言·mybatis
gaoshan1234567891013 小时前
‌MyBatis-Plus 的 LambdaQueryWrapper 可以实现 OR 条件查询‌
java·tomcat·mybatis
The best are water20 小时前
jeesite mybatis添加拦截器,推送指定表的变更数据到其他数据库
数据库·mybatis
lunz_fly199221 小时前
【源码解读之 Mybatis】【核心篇】-- 第6篇:StatementHandler语句处理器
mybatis
lunzi_fly21 小时前
【源码解读之 Mybatis】【核心篇】-- 第6篇:StatementHandler语句处理器
mybatis
optimistic_chen1 天前
【Java EE进阶 --- SpringBoot】Mybatis操作数据库(基础二)
xml·数据库·spring boot·笔记·java-ee·mybatis
ss2731 天前
手写MyBatis第107弹:@MapperScan原理与SqlSessionTemplate线程安全机制
java·开发语言·后端·mybatis
二宝1522 天前
黑马商城day1-MyBatis-Plus
java·开发语言·mybatis
龙猫蓝图2 天前
wrapper+ xml文件进行SQL编写
mybatis