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

初始数据库数据

结果

相关推荐
曾经的三心草19 小时前
redis-9-集群
java·redis·mybatis
识君啊19 小时前
MyBatis-Plus 逻辑删除导致唯一索引冲突的解决方案
java·spring boot·mybatis·mybatis-plus·唯一索引·逻辑删除
架构师刘伟20 小时前
MyBatis-Dynamic 进阶:无需实体类的全动态数据建模
mybatis
那我掉的头发算什么21 小时前
【Mybatis】Mybatis-plus使用介绍
服务器·数据库·后端·spring·mybatis
czlczl200209251 天前
缓存穿透问题与解决方案
缓存·mybatis
程序员侠客行1 天前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
老毛肚2 天前
手写mybatis
java·数据库·mybatis
爱学英语的程序员2 天前
面试官:你了解过哪些数据库?
java·数据库·spring boot·sql·mysql·mybatis
阿杰真不会敲代码2 天前
Mybatis-plus入门到精通
java·tomcat·mybatis
侠客行03172 天前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读