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

初始数据库数据

结果

相关推荐
碎碎念_49214 小时前
SpringBoot和MyBatis框架·速通版
spring boot·后端·mybatis
唐青枫14 小时前
Java MyBatis 实战指南:XML 映射、动态 SQL 与数据访问层设计
java·mybatis
一条泥憨鱼15 小时前
苍穹外卖【day3|菜品管理】
java·数据库·sql·mysql·mybatis
INFINI Labs1 天前
Elasticsearch 6/7/8 到 Easysearch 2.x 迁移指南
大数据·elasticsearch·mybatis·向量·snapshot
CodeStats2 天前
从JDBC时代到MyBatis封神:SQL全流程手写ORM实战
sql·mysql·mybatis
我登哥MVP2 天前
Spring Boot 从“会用”到“精通”:参数绑定体系全景
java·spring boot·spring·servlet·maven·intellij-idea·mybatis
唐青枫2 天前
Java MyBatis-Plus 实战指南:用 BaseMapper、Wrapper 和分页写好数据层
java·mybatis
我登哥MVP3 天前
Spring Boot 从“会用”到“精通”:Model-Map原理
java·spring boot·后端·spring·servlet·maven·mybatis
Full Stack Developme3 天前
MyBatis-Plus 分页使用详解
mybatis
落木萧萧8253 天前
MyBatisGX 批量操作:比 MyBatis-Plus 和 MyBatis-Flex 更好用、更快
mybatis·orm