Mybatis学习之自定义持久层框架(五) 自定义持久层框架:封装CRUD操作
前言
上一篇文章我们完成了生产sqlSession的工作,与数据库的连接和创建会话的工作都已完成,今天我们可以来决定会话的内容了。
封装CRUD操作
首先我们需要创建一个SqlSession接口类,在其中定义会话的内容接口,同样,今天所提及的类都存放在“sqlSession”包下,SqlSession接口类的代码如下所示:
1 package com.hardy.sqlSession; 2 3 import java.sql.SQLException; 4 import java.util.List; 5 6 public interface SqlSession { 7 8 //为Dao接口生成代理实现类 9 publicT getMapper(Class<?> mapperClass); 10 11 public void close() throws SQLException; 12 13 /* 查询所有: 14 根据statementId,找到Mapper.xml文件中对应的sql语句 15 Object...Parameter 表示支持传递多个参数值进行查询 16 */ 17 public List selectList(String statementId, Object... Parameter) throws Exception; 18 19 // 根据条件查询单个 20 public T selectOne(String statementId, Object... Parameter) throws Exception; 21 22 }
为方便由浅入深地学习,我们暂时之定义查询单个和查询列表的接口。
编写完接口类,就到实现类这里了,在相同包下创建一个DefaultSqlSession,编写如下代码:
1 package com.hardy.sqlSession; 2 3 import com.hardy.pojo.Configuration; 4 import com.hardy.pojo.MappedStatement; 5 import com.hardy.pojo.SqlOperationEnum; 6 7 import java.beans.IntrospectionException; 8 import java.lang.reflect.*; 9 import java.sql.SQLException; 10 import java.util.List; 11 12 public class DefaultSqlSession implements SqlSession { 13 14 // 处理器对象 15 private Executor simpleExecutor = new SimpleExecutor(); 16 17 private Configuration configuration; 18 19 public DefaultSqlSession(Configuration configuration) { 20 this.configuration = configuration; 21 } 22 23 @Override 24 publicList selectList(String statementId, Object... params) throws Exception { 25 // 未完,待续 26 MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId); 27 28 return (List ) list; 29 } 30 31 @Override 32 public T selectOne(String statementId, Object... params) throws Exception { 33 List
总结
今天暂时先定义好了sqlSession相关的接口,下一篇文章会实现真正的CRUD操作调用类,然后就可以在DefaultSqlSession中对其进行调用了。