Use XSD to verify the SqlMapper configuration file of Mybatis (1), xsdsqlmapper

Source: Internet
Author: User

Use XSD to verify the SqlMapper configuration file of Mybatis (1), xsdsqlmapper

This article is based on the reconstruction of SqlSessionFactoryBean. Let's briefly review what operations have been done:

Now let's look at how to scale it. First, create SchemaSqlSessionFactoryBean, inherit the restructured SqlSessionFactoryBean, and change it to the new class in XML Configuration:

public class SchemaSqlSessionFactoryBean extends SqlSessionFactoryBean {}

For some simple function extensions, such as setting the default result type and scanning the specified type for short, we will not discuss much here. Here we will focus on how to extend it to use XSD to verify SqlMapper configurations.

1. overwrite the doParseSqlMapperResource () method in SqlSessionFactoryBean. The function of this method is to parse a SqlMapper configuration file.

Of course, to ensure compatibility, you must first determine whether it is a DTD. If it is a DTD, use the original method for parsing; otherwise, use the custom method for parsing:

Package org. dysd. dao. mybatis. schema; import org.apache.ibatis.exe cutor. errorContext; import org. apache. ibatis. session. configuration; import org. springframework. core. nestedIOException; import org. springframework. core. io. resource; import org. springframework. util. xml. extends; public class extends SqlSessionFactoryBean {@ Override protected void doParseSqlMapperResource (Configuration configuration, Resource mapperLocation) throws NestedIOException {int mode = detectValidationMode (mapperLocation); if (mode = callback. VALIDATION_DTD) {// if it is a DTD, use the official Mybatis 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: '" + mapperLocation + "'", e);} finally {ErrorContext. instance (). reset () ;}return mode ;}}View Code

The XmlValidationModeDetector in Spring is used to detect the validation mode of the XML configuration file. The logic is also very simple, that is, one row of reading. before the beginning of the body, if a dtd definition is found, the DTD mode is returned, otherwise, the XSD mode is returned. (In fact, not only does the detection mode borrow Spring, but also the custom namespace follows Spring ).

At this point, the parsing of the SqlMapper configuration file has been divided into two, compatible with the official mybatis parsing, and navigate the parsing in XSD mode to the doParseSqlMapperResourceWithSchema () method.

2. Compile the XSD file used to verify SqlMapper (you must have basic XSD knowledge. Refer to the learning notes on XML in this blog)

1. Use an XML tool to convert the DTD file of Mybatis to the original XSD file. Many XML tools have this function. You can search for it online.

There are three levels:

(1) root element (mapper element): corresponds to a SqlMapper file and has a namespace attribute, indicating a logical classification of its child elements. Note that the namespace attribute here is different from the XML namespace. The former is a logical classification of mybatis, the latter is used to define XML elements and attribute constraints that can appear in xml files.

(2) Level 1 subelement (cache | cache-ref | resultMap | parameterMap | SQL | insert | update | delete | select): Level 1 subelement of mapper, because the mybatis framework has different processing methods for level 1 sub-elements, it is used as a level separately here. Because it mainly involves adding, deleting, modifying, and querying statements, it is called a statement level statement element.

(3) Other elements (SQL configuration text, include | trim | where | set | foreach | choose | if): the text used to configure SQL scripts and dynamic script elements, it is called a script-level script element.

2. Make the following changes on the basis of generating the XSD file:

(1) Add a namespace, for example:

<?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 a level-1 element into an element group statementGroup

(3) modify the mapper element to allow other namespace Elements

(4) wrap the dynamic script element into an element group dynaScriptGroup and allow other named elements to appear.

(5) Use dynaScriptGroup to replace the location where the dynamic script elements appear, such as the <select> element.

(6) Other optimizations, such as defining STATEMENT, PREPARED, and CALLABLE values that can be obtained 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>

Similarly, there are parameterMode, jdbcType, javaType, and so on.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.