Method of using XSD to validate MyBatis sqlmapper configuration files (1) _java

Source: Internet
Author: User
Tags xmlns

This article used to be based on the refactoring of Sqlsessionfactorybean, a brief review of what has been done:

New Sqlsessionfactorybean, the original code and mybatis-spring the same;

The Buildsqlsessionfactory () method is used to extract a large number of if statements into a group of small methods, reserving the custom configuration method, and adding the getter method of common attributes;

Extracts the component factory interface and provides component creation tool class Sqlsessioncomponetfactorys, which will be scattered in different places in the new Xxx () centrally managed to facilitate the replacement of components.

Now to see how to expand, first create the Schemasqlsessionfactorybean, inherit the reconstructed Sqlsessionfactorybean, and synchronize the changes in the XML configuration to the newly created class:

public class Schemasqlsessionfactorybean extends Sqlsessionfactorybean {
}

For some simple feature extensions, such as setting the default result type, scanning for the specified type abbreviation, this is not much discussed here, which focuses on how to extend to use XSD checksum sqlmapper configuration.

The Doparsesqlmapperresource () method in the overlay Sqlsessionfactorybean, the function of this method is to parse a sqlmapper configuration file

Of course, in order to be compatible, you need to first determine if it is a DTD, and if it is a DTD, parse it in the original way, otherwise, by a 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 {@Override protected void Doparsesqlmapperresource (Configuration Configuration, Resource mapperlocation) throws nestedioexception {int mode =
Detectvalidationmode (mapperlocation); if (mode = = XMLVALIDATIONMODEDETECTOR.VALIDATION_DTD) {//If it is a DTD, use the MyBatis official parsing super.doparsesqlmapperresource (
Configuration, mapperlocation); }else{try {//Use schema checksum 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; }
}

This borrows the xmlvalidationmodedetector in spring to detect the checksum mode of the XML configuration file, which is logically simple enough to read in one line, to return to the DTD pattern when a DTD definition is found before the body begins, otherwise the XSD pattern is returned (in fact, Not only does the reconnaissance pattern borrow spring, but the following custom namespaces also draw on spring.

At this point, the parsing of the Sqlmapper configuration file has been divided into two, compatible with the mybatis of the official parsing, and the XSD mode of resolution navigation to the method Doparsesqlmapperresourcewithschema ().

Ii. write XSD files for validating sqlmapper (you need some XSD basics, refer to the XML section of this blog for learning notes)

1, first use an XML tool, the MyBatis DTD file into the original XSD file, there are many XML tools have this function, you can search the Internet

This is divided into three levels:

(1) root element (mapper Element): corresponding to a sqlmapper file, there is a namespace attribute that represents a logical classification of its child elements. Note that the namespace property here differs from the XML namespace, which is a logical classification of the MyBatis itself, which is used to define XML elements and attribute constraints that can occur in an XML file.

(2) One-level child element (Cache|cache-ref|resultmap|parametermap|sql|insert|update|delete|select): The first-level child element of the Mapper, Because the MyBatis framework has different processing of a level of child elements, so here alone as a hierarchy, because the main is to delete and check the statement, so called the statement-level statement elements

(3) Other elements (SQL configuration text, include|trim|where|set|foreach|choose|if): Text used to configure SQL scripts, as well as dynamic scripting elements, called scripting-level script elements

2. Make the following modifications on the basis of generating XSD files

(1) Add namespaces, such as:

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"?> <xsd:schema
"xmlns=" Sqlmapper "
targetnamespace=" Http://dysd.org/schema/sqlmapper "
xmlns:xsd=" http://www.w3.org/2001/ XmlSchema " 
elementformdefault=" qualified "version=" 1.0 ">

(2) Packaging the first-level elements into an element group Statementgroup

(3) Modifying the mapper element, allowing elements of other namespaces to appear

(4) Wrapping a dynamic script element as an element group Dynascriptgroup and allowing other named elements to appear

(5) Use Dynascriptgroup to replace places where dynamic scripting elements occur, such as <select> elements

(6) Other optimizations, such as statement, PREPARED, and callable, which can be statementtype, are defined as enumerated types:

<xsd:simpletype name= "StatementType" >
<xsd:restriction base= "Xsd:token" >
<xsd:enumeration Value= "STATEMENT"/> <xsd:enumeration value= "PREPARED"/> <xsd:enumeration "value="
/ >
</xsd:restriction>
</xsd:simpleType>

Similar to Parametermode, Jdbctype, Javatype and so on.

The above is a small series to introduce the use of XSD checksum mybatis sqlmapper configuration file Summary, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.