传统开发方式
编写UserDao接口
1
2
3
|
public interface UserMapper { public List<User> findAll() throws IOException; } |
编写UserDaompl实现
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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; } } |
传统测试方法
1
2
3
4
5
6
7
8
|
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文件中的
namespace
与mapper
接口的全限定名相同 -
2、Mapper接口方法名和Mapper.xml中定义的每个
Statement
的id相同 -
3、Mapper接口方法的输入参数类型和Mapper.xml中定义的每个sql的
parameterType
的类型相同 -
4、Mapper接口方法的输出参数类型和Mapper.xml中定义的每个sql的
resultType
的类型相同
编写UserMapper接口
测试代理方法
接口:
1
2
3
|
public interface UserMapper { public List<User> findAll() ; } |
测试代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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查询:
接口:
1
2
3
4
|
public interface UserMapper { //根据id查询 public User findById( int id); } |
测试:
1
2
3
|
UserMapper mapper = sqlSession.getMapper(UserMapper. class ); User user=mapper.findById( 2 ); System.out.println(user); |
到此这篇关于MyBatis详解如何实现Dao层接口的文章就介绍到这了,更多相关MyBatis Dao层接口内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_47383392/article/details/123948625