This article was previously based on the reconstruction of SqlSessionFactoryBean, so I will briefly review what operations I did:
Create a new SqlSessionFactoryBean, and the initial code is the same as mybatis-spring;
Refactor the buildSqlSessionFactory() method, extract numerous if statements into a set of small methods, reserve custom configuration methods, and add common attributes getter methods;
Extract component factory interfaces and provide component creation tool class SqlSessionComponetFactorys, which centrally manages new Xxx() scattered in different places to facilitate component replacement.
Now let’s look at how to expand. First, create a SchemaSqlSessionFactoryBean, inherit the refactored SqlSessionFactoryBean, and synchronize it to a newly created class in the XML configuration:
public class SchemaSqlSessionFactoryBean extends SqlSessionFactoryBean {}For some simple function extensions, such as setting the default result type and scanning the specified type abbreviation, I will not discuss it much here. Here I will focus on how to expand to verify the configuration of SqlMapper using XSD.
1. Overwrite the doParseSqlMapperResource() method in SqlSessionFactoryBean. The function of this method is to parse a SqlMapper configuration file.
Of course, for compatibility, you need to first determine whether it is DTD. If it is DTD, analyze it according to the original method, otherwise analyze it according to the custom method:
package org.dysd.dao.mybatis.schema;import org.apache.ibatis.executor.ErrorContext;import org.apache.ibatis.session.Configuration;import org.springframework.core.NestedIOException;import org.springframework.core.io.Resource;import org.springframework.util.xml.XmlValidationModeDetector;public class SchemaSqlSessionFactoryBean extends SqlSessionFactoryBean {@Overrideprotected void doParseSqlMapperResource(Configuration configuration, Resource mapperLocation)throws NestedIOException {int mode = detectValidationMode(mapperLocation);if(mode == XmlValidationModeDetector.VALIDATION_DTD){//If it is DTD, use Mybatis official parsing super.doParseSqlMapperResource(configuration, mapperLocation);}else{try {// Use Schema to verify this.doParseSqlMapperResourceWithSchema(configuration, mapperLocation);} catch (Exception e) {throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);} finally {ErrorContext.instance().reset();}}} protected void doParseSqlMapperResourceWithSchema(Configuration configuration, Resource mapperLocation){}private int detectValidationMode(Resource mapperLocation) throws NestedIOException {int mode = -1;try {XmlValidationModeDetector detector = new XmlValidationModeDetector();mode = detector.detectValidationMode(mapperLocation.getInputStream());} catch (Exception e) {throw new NestedIOException("Failed to parse mapping resource: '" + mappperLocation + "'", e);} finally {ErrorContext.instance().reset();} return mode;}}Here we borrow the XmlValidationModeDetector in Spring to detect the verification mode of XML configuration files. It is logically simple, just read one line by one. Before the text starts, if you find that there is a dtd definition, you will return the DTD mode, otherwise you will return the XSD mode (in fact, not only the detection mode borrows Spring, but also the custom namespace behind it also borrows Spring).
At this point, the parsing of the SqlMapper configuration file has been divided into two branches, which are compatible with the official parsing of mybatis, and the parsing in XSD mode is navigated to the method doParseSqlMapperResourceWithSchema().
2. Write an XSD file for verification of SqlMapper (requires some basic knowledge of XSD, please refer to the study notes on the XML part in this blog)
1. First use an XML tool to convert Mybatis' DTD file into original XSD file. There are many XML tools that have this function. You can search online.
Here are three levels:
(1) Root element (mapper element): corresponding to a SqlMapper file, there is a namespace attribute, representing a logical classification of its child elements. It should be noted that the namespace attribute here is different from the XML namespace. The former is a logical classification of mybatis itself, and the latter is used to define the XML elements and attribute constraints that can appear in XML files.
(2) First-level child elements (cache|cache-ref|resultMap|parameterMap|sql|insert|update|delete|select): The first-level child elements of mapper. Because the mybatis framework has different processing of first-level child elements, it is used as a separate level. Because it mainly adds, deletes, and changes to check statements, it is called a statement-level statement element.
(3) Other elements (SQL configuration text, include|trim|where|set|foreach|choose|if): text used to configure SQL scripts, as well as dynamic script elements, called script-level script elements
2. Make the following modifications based on the generation of XSD files
(1) Add a namespace, such as:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><xsd:schema xmlns="http://dysd.org/schema/sqlmapper"targetNamespace="http://dysd.org/schema/sqlmapper"xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" version="1.0">
(2) Package the first-level element into an element group statementGroup
(3) Modify the mapper element to allow elements in other namespaces to appear
(4) Wrapping dynamic script elements into an element group dynaScriptGroup and allowing other named elements to appear
(5) Use dynaScriptGroup to replace where dynamic script elements appear, such as <select> elements
(6) Some other optimizations, such as defining the three values STATEMENT, PREPARED, and CALLABLE that can be taken by statementType as enumeration types:
<xsd:simpleType name="statementType"><xsd:restriction base="xsd:token"><xsd:enumeration value="STATEMENT" /><xsd:enumeration value="PREPARED" /><xsd:enumeration value="CALLABLE" /></xsd:restriction></xsd:simpleType>
Similar ones include parameterMode, jdbcType, javaType, etc.
The above is the summary of the SqlMapper configuration file used by XSD to verify Mybatis. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!