自定義持久層框架
下圖是JDBC引起的一系列問題以及解決辦法:

自定義持久層框架設計思路:
使用端(專案):引入自定義持久層框架jar包,
提供兩部分配置資訊:1,資料庫配置資訊;2,sql配置資訊--(sql陳述句、引數型別、回傳值型別)
解決辦法:使用組態檔來提供兩部分配置資訊:
<1>sqlMapConfig.xml:放資料庫配置資訊;在sqlMapConfig.xml中,其實也可以存放mapper.xml的全路徑,方法getResourceAsSteam()可以一次性全部讀取;
<2>mapper.xml:存放sql配置資訊;自定義持久層框架本身(工程):本質上就是對JDBC代碼進行了封裝,
(1)加載組態檔,根據組態檔的路徑,加載組態檔成位元組輸入流,存盤在記憶體中;
創建Resource類
方法:getResourceAsSteam(String path)回傳 InputSteam;(2)創建兩個javaBean(容器物件):存放的就是對組態檔決議出來的內容,如下:
Configruation核心配置類:存放sqlMapConfig.xml決議出來的內容;
MappedStatement映射配置類:存放mapper.xml決議出來的內容;(3)決議組態檔,可以采用dom4j對組態檔進行決議;
創建類:SqlSessionFactoryBuilder,方法:build(InputSteam is)
<1>使用dom4j決議組態檔,將決議出來的內容封裝到容器物件中;
<2>創建SqlSessionFactory物件;主要作用就是利用工廠模式生產sqlSession(會話物件)(4)基于開閉原則創建SqlSessionFactory介面及實作類DefaultSqlSessionFactory
<1>生產sqlSession【openSqlSession()】(5)創建SqlSession介面及實作類DefaultSession
定義對資料庫的crud操作:selectList()selectOne()update()delete()(6)創建Exeutor介面及實作類SimpleExeutor實作類,執行的就是JDBC代碼;
query(Configruation,MappedStatement,Object ... params);
創建兩個maven工程IPersistence和IPersistence_test
--IPersistence_test引入IPersistence依賴--
?
<groupId>com.yun</groupId>
<artifactId>IPersistence_test</artifactId>
<version>1.0-SNAPSHOT</version>
?
<!--引入自定義持久層框架依賴-->
<dependencies>
<dependency>
<groupId>com.yun</groupId>
<artifactId>IPersistence</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
--IPersistence_test-->sqlMapConfig.xml--
<configuration>
<!--資料庫配置資訊-->
<dataSource>
<property name="driverClass" value="https://www.cnblogs.com/wangshaoyun/p/com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="https://www.cnblogs.com/wangshaoyun/p/jdbc:mysql://xxx.xxx.xx.xxx:xxxx/xxxx"></property>
<property name="username" value="https://www.cnblogs.com/wangshaoyun/p/xxxx"></property>
<property name="password" value="https://www.cnblogs.com/wangshaoyun/p/xxxx"></property>
</dataSource>
<!--存放mapper.xml的全路徑-->
<mapper resource="userMapper.xml"></mapper>
</configuration>
--IPersistence_test-->userMapper.xml--
<mapper namespace="user">
<!--sql的唯一標識應該是由 namespace.id來組成(statementId)-->
<select id="selectList" resultType="com.yun.pojo.User">
select * from user
</select>
<!--利用反射獲取到user物件的引數-->
<select id="selectOne" resultType="com.yun.pojo.User" paramterType="com.yum.pojo.User">
select * from user where id = #{id} and username = #{username}
</select>
</mapper>
--IPersistence--
@Data
public class MappedStatement {
//id
private Integer id;
//回傳值型別
private String resultType;
//引數值型別
private String paramterType;
//sql陳述句
private String sql;
}
--IPersistence--
@Data
public class Configuration {
private DataSource dataSource;
/**
* k:statementId
* v:封裝好的MappedStatement物件
*/
Map<String,MappedStatement> map = new HashMap<>();
}
按照設計思路撰寫代碼
--決議組態檔回傳流
public class Resources {
/**
* 根據組態檔的路徑,將組態檔加載成位元組輸入流,存盤在記憶體中
* @param path
* @return
*/
public static InputStream getResourcesAsSteam(String path){
InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
return resourceAsStream;
}
}
@Data
public class Configuration {
private DataSource dataSource;
/**
* k:statementId
* v:封裝好的MappedStatement物件
*/
Map<String,MappedStatement> map = new HashMap<>();
}
@Data
public class MappedStatement {
//id
private String id;
//回傳值型別
private String resultType;
//引數值型別
private String paramterType;
//sql陳述句
private String sql;
}
--將決議的流封裝到SqlSessionFactoryBuilder中
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream is) throws Exception {
//1,使用dom4j決議組態檔,將決議出來的內容封裝到Configuration中
XmlConfigBuilder xmlConfigBuilder = new XmlConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfig(is);
//2,創建sqlSessionFactory物件,工廠類:生產sqlSession繪畫物件
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return defaultSqlSessionFactory;
}
}
--將sqlMapConfig.xml和userMapper.xml流放入configuration中
public class XmlConfigBuilder {
private Configuration configuration;
public XmlConfigBuilder() {
this.configuration = new Configuration();
}
/**
* 該方法就是使用dom4j將組態檔決議,封裝Configuration
* @param is
* @return
*/
public Configuration parseConfig(InputStream is) throws Exception {
Document document = new SAXReader().read(is);
//獲取Configuration根物件<Configuration>
Element rootElement = document.getRootElement();
//獲取sqlMapConfig.xml里面的配置資訊并且遍歷
List<Element> list = rootElement.selectNodes("//property");
Properties properties = new Properties();
for (Element element : list) {
String name = element.attributeValue("name");
String value = https://www.cnblogs.com/wangshaoyun/p/element.attributeValue("value");
properties.setProperty(name,value);
}
//創建 c3p0 連接池
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
comboPooledDataSource.setUser(properties.getProperty("username"));
comboPooledDataSource.setUser(properties.getProperty("password"));
configuration.setDataSource(comboPooledDataSource);
//mapper.xml決議 步驟:拿到路徑-->加載成位元組輸入流-->dom4j進行決議
List<Element> mapperList = rootElement.selectNodes("//mapper");
for (Element element : mapperList) {
String mapperPath = element.attributeValue("resource");
InputStream resourcesAsSteam = Resources.getResourcesAsSteam(mapperPath);
XmlMApperBuilder xmlMApperBuilder = new XmlMApperBuilder(configuration);
xmlMApperBuilder.prase(resourcesAsSteam);
}
return configuration;
}
}
public class XmlMApperBuilder {
private Configuration configuration;
public XmlMApperBuilder(Configuration configuration) {
this.configuration = configuration;
}
public void prase(InputStream is) throws Exception {
Document document = new SAXReader().read(is);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributeValue("namespace");
List<Element> list = rootElement.selectNodes("//select");
for (Element element : list) {
String id = element.attributeValue("id");
String resultType = element.attributeValue("resultType");
String paramterType = element.attributeValue("paramterType");
String sqlText = element.getTextTrim();
MappedStatement mappedStatement = new MappedStatement();
mappedStatement.setId(id);
mappedStatement.setResultType(resultType);
mappedStatement.setParamterType(paramterType);
mappedStatement.setSql(sqlText);
//key值是由 namespace.id來組成
String key = namespace +"."+id;
configuration.getMap().put(key,mappedStatement);
}
}
}
--利用工廠模式生產sqlSession
public class DefaultSqlSessionFactory implements SqlSessionFactory{
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration);
}
}
@AllArgsConstructor
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
@Override
public <E> List<E> selectList(String statementId, Object... params) throws Exception {
//將要去完成對 SimpleExecutor 里的query方法的呼叫
SimpleExecutor simpleExecutor = new SimpleExecutor();
MappedStatement mappedStatement = configuration.getMap().get(statementId);
List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
return (List<E>) list;
}
@Override
public <T> T selectOne(String statementId, Object... params) throws Exception {
List<Object> objects = selectList(statementId, params);
if (objects.size() == 1) {
return (T) objects.get(0);
} else {
throw new RuntimeException("查詢結果為慷訓者回傳結果過多");
}
}
}
--注冊驅動,查詢資料資訊 并且封裝回傳
public class SimpleExecutor implements Executor {
@Override //user
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception{
//1,注冊驅動,獲取連接
Connection connection = configuration.getDataSource().getConnection();
//2,獲取sql select * from user where id = #{id} and username = #{username}
//轉換sql select * from user where id = ? and username = ?,轉換程序中,還需要對#{}里面的值進行存盤決議
String sql = mappedStatement.getSql();
BoundSql boundSql = getBoundSql(sql);
//3,獲取預處理物件
PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
//4,設定引數
//獲取到引數的全路徑
String paramterType = mappedStatement.getParamterType();
Class<?> paramterTypeClass = getClassType(paramterType);
List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
for (int i = 0; i < parameterMappingList.size(); i++) {
ParameterMapping parameterMapping = parameterMappingList.get(i);
String content = parameterMapping.getContent();
//反射根據content獲取到物體物件中的屬性值,再根據屬性值獲取到當前傳過來的引數物件
Field declaredField = paramterTypeClass.getDeclaredField(content);
//暴力訪問
declaredField.setAccessible(true);
Object o = declaredField.get(params[0]);
preparedStatement.setObject(i+1,o);
}
//5,執行sql
ResultSet resultSet = preparedStatement.executeQuery();
//獲取物體物件
String resultType = mappedStatement.getResultType();
Class<?> resultTypeClass = getClassType(resultType);
//獲取物體物件的具體實作
Object instance = resultTypeClass.newInstance();
List<Object> objects = new ArrayList<>();
//6,封裝回傳結果集
while (resultSet.next()) {
//1,取出元資料
ResultSetMetaData metaData = https://www.cnblogs.com/wangshaoyun/p/resultSet.getMetaData();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
//獲取欄位名
String columnName = metaData.getColumnName(i);
//獲取欄位值
Object value = resultSet.getObject(columnName);
//使用反射或者內省根據資料庫表和物體的對應關系,完成封裝
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(instance,value);
}
objects.add(instance);
}
return (List) objects;
}
/**
* 反射獲取物體
* @param paramterType
* @return
* @throws Exception
*/
private Class<?> getClassType(String paramterType) throws Exception {
if (StringUtils.isNullOrEmpty(paramterType)) {
Class<?> aClass = Class.forName(paramterType);
return aClass;
}
return null;
}
/**
* 完成對#{}的決議作業:1,將#{}使用?進行代替;2,決議出#{}里面的值進行存盤
* @param sql
* @return
*/
private BoundSql getBoundSql(String sql) {
//標記處理類:配置標記決議器來完成對占位符的決議處理作業
ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
//標記決議器,對占位符的轉換
GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", tokenHandler);
//決議出來的sql
String parseSql = tokenParser.parse(sql);
//#{}里面的決議出來的引數名稱
List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
return boundSql;
}
}
開始測驗
public class IPersistenceTest {
@Test
public void test() throws Exception {
//獲取組態檔流
InputStream resourcesAsSteam = Resources.getResourcesAsSteam("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourcesAsSteam);
SqlSession sqlSession = sqlSessionFactory.openSession();
//呼叫
User user = new User();
user.setId(1);
user.setUsername("張三");
User user2 = sqlSession.selectOne("user.selectOne", user);
System.out.println(user2);
}
}
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/466955.html
標籤:Java
上一篇:Spring Boot
