MyBatis Dao层接口

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

MyBatis Dao层接口

Tangable22   2022-05-28 我要评论

传统开发方式

编写UserDao接口

public interface UserMapper {
    public List<User> findAll() throws IOException;
}

编写UserDaompl实现

public class UserMapperImp implements UserMapper {

    @Override
    public List<User> findAll() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession();

        List<User> users=sqlSession.selectList("User.findAll");
        sqlSession.close();
        return users;
    }
}

传统测试方法

public class ServiceCode {
    public static void main(String[] args) throws IOException {
        UserMapper userMapper = new UserMapperImp();
        List<User> all = userMapper.findAll();

        System.out.println(all);
    }
}

我们发现使用传统的开发方式,每次都要实现接口的代码编写,这样也有很多的代码冗余,也是相当的繁琐,下面,MyBatis为我们提供了代理开发的方法,我们只需要提供接口,MyBatis框架就可以根据接口定义为我们实现。

代理开发方法

代理开发方式介绍

采用MyBatis的代理开发方式实现Dao层的开发,这种方式是我们后面进入企业的主流。

Mapper接口开发方法只需要程序员编写Mapper接口(相当与Dao接口),由MyBatis框架根据接口定义创建接口的动态代理对象,代理对象方法体同上边Dao接口实现类方法。

Mapper接口开发需要遵循一下规范:

  • 1、Mapper.xml文件中的namespacemapper接口的全限定名相同
  • 2、Mapper接口方法名和Mapper.xml中定义的每个Statement的id相同
  • 3、Mapper接口方法的输入参数类型和Mapper.xml中定义的每个sql的parameterType的类型相同
  • 4、Mapper接口方法的输出参数类型和Mapper.xml中定义的每个sql的resultType的类型相同

编写UserMapper接口

在这里插入图片描述

测试代理方法

接口:

public interface UserMapper {
    public List<User> findAll() ;
}

测试代码:

public class Test {
    public static void main(String[] args) throws Exception {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new 				    				SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获得MyBatis框架生产的UserMapper接口的实现类
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<user> all = mapper.findAll();

        for (user user : all) {
            System.out.println(user);
        }
    }

根据id查询:

接口:

public interface UserMapper {
    //根据id查询
    public User findById(int id);
}

测试:

UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user=mapper.findById(2);
System.out.println(user);

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们