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、测试

初始数据库数据

结果

相关推荐
sensenlin9111 小时前
Mybatis中SQL全大写或全小写影响执行性能吗
数据库·sql·mybatis
BXCQ_xuan11 小时前
软件工程实践四:MyBatis-Plus 教程(连接、分页、查询)
spring boot·mysql·json·mybatis
wuyunhang12345612 小时前
Redis----缓存策略和注意事项
redis·缓存·mybatis
lunz_fly199214 小时前
【源码解读之 Mybatis】【基础篇】-- 第2篇:配置系统深度解析
mybatis
森林-15 小时前
MyBatis 从入门到精通(第一篇)—— 框架基础与环境搭建
java·tomcat·mybatis
森林-15 小时前
MyBatis 从入门到精通(第三篇)—— 动态 SQL、关联查询与查询缓存
sql·缓存·mybatis
java干货18 小时前
MyBatis 的“魔法”:Mapper 接口是如何找到并执行 SQL 的?
数据库·sql·mybatis
嬉牛1 天前
项目日志输出配置总结(多数据源MyBatis+Logback)
mybatis·logback
哈喽姥爷3 天前
Spring Boot--yml配置信息书写和获取
java·数据库·spring boot·mybatis
奔跑你个Run3 天前
mybatis plus 使用wrapper输出SQL
mybatis