MyBatis Hot Load Mapper.xml

Source: Internet
Author: User

Development, write MyBatis Mapper.xml file, each time the SQL needs to restart the service, feel very troublesome, so try to write a mybatis mapper.xml hot load.

Can reload MyBatis after modifying Mapper.xml, can use it when developing.

Spring Configuration:

<id= "Mybatismapperdynamicloader"  class= " Com.teststartup.MybatisMapperDynamicLoader "/>


Java code:

Importjava.io.IOException;ImportJava.lang.reflect.Field;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Set;ImportJava.util.Timer;ImportJava.util.TimerTask;ImportOrg.apache.ibatis.builder.xml.XMLMapperBuilder;ImportOrg.apache.ibatis.executor.ErrorContext;Importorg.apache.ibatis.session.Configuration;Importorg.apache.ibatis.session.SqlSessionFactory;Importorg.springframework.beans.BeansException;ImportOrg.springframework.beans.factory.InitializingBean;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.ApplicationContextAware;ImportOrg.springframework.context.ConfigurableApplicationContext;Importorg.springframework.core.NestedIOException;ImportOrg.springframework.core.io.Resource;ImportOrg.springframework.core.io.support.PathMatchingResourcePatternResolver;ImportOrg.springframework.core.io.support.ResourcePatternResolver; Public classMybatismapperdynamicloaderImplementsInitializingbean, Applicationcontextaware {Private Finalhashmap<string, string> mappers =NewHashmap<string, string>(); Private volatileConfigurableapplicationcontext context =NULL; Private volatileScanner Scanner =NULL; @Override Public voidSetapplicationcontext (ApplicationContext ApplicationContext)throwsbeansexception { This. Context =(Configurableapplicationcontext) ApplicationContext; } @Override Public voidAfterpropertiesset ()throwsException {Try{Scanner=NewScanner (); NewTimer (true). Schedule (NewTimerTask () { Public voidrun () {Try {                        if(scanner.ischanged ()) {System.out.println ("Load Mapper.xml");                        Scanner.reloadxml (); }                    } Catch(Exception e) {e.printstacktrace (); }                }            }, 10 * 1000, 5 * 1000); } Catch(Exception E1) {e1.printstacktrace (); }} @SuppressWarnings ("Unchecked")    classScanner {Private Static FinalString Xml_resource_pattern = resourcepatternresolver.classpath_all_url_prefix + "**/*sql.xml"; Private FinalResourcepatternresolver Resourcepatternresolver =NewPathmatchingresourcepatternresolver ();  PublicScanner ()throwsIOException {resource[] resources=FindResource (); if(Resources! =NULL) {                 for(Resource resource:resources) {String key=Resource.geturi (). toString (); String value=GETMD (Resource);                Mappers.put (key, value); }            }        }         Public voidReloadxml ()throwsException {sqlsessionfactory Factory= Context.getbean (sqlsessionfactory.class); Configuration Configuration=factory.getconfiguration ();            Removeconfig (configuration);  for(Resource Resource:findresource ()) {Try{xmlmapperbuilder Xmlmapperbuilder=NewXmlmapperbuilder (Resource.getinputstream (), Configuration, resource.tostring (), configuration.getsqlfragments                    ());                Xmlmapperbuilder.parse (); } finally{errorcontext.instance (). reset (); }            }        }        Private voidRemoveconfig (Configuration configuration)throwsException {Class<?> Classconfig =Configuration.getclass (); Clearmap (classconfig, configuration,"Mappedstatements"); Clearmap (classconfig, configuration,"Caches"); Clearmap (classconfig, configuration,"Resultmaps"); Clearmap (classconfig, configuration,"Parametermaps"); Clearmap (classconfig, configuration,"Keygenerators"); Clearmap (classconfig, configuration,"Sqlfragments"); Clearset (classconfig, configuration,"Loadedresources"); }        Private voidClearmap (class<?> classconfig, configuration configuration, String fieldName)throwsException {Field field=Classconfig.getdeclaredfield (fieldName); Field.setaccessible (true); ((Map) field.get (configuration). Clear (); }        Private voidClearset (class<?> classconfig, configuration configuration, String fieldName)throwsException {Field field=Classconfig.getdeclaredfield (fieldName); Field.setaccessible (true); ( Set) field.get (configuration). Clear (); }         Public BooleanIschanged ()throwsIOException {BooleanIschanged =false;  for(Resource Resource:findresource ()) {String key=Resource.geturi (). toString (); String value=GETMD (Resource); if(!value.equals (Mappers.get (key))) {ischanged=true;                Mappers.put (key, value); }            }            returnischanged; }        PrivateResource[] FindResource ()throwsIOException {returnresourcepatternresolver.getresources (Xml_resource_pattern); }        PrivateString GETMD (Resource Resource)throwsIOException {return NewStringBuilder (). Append (Resource.contentlength ()). Append ("-"). Append (Resource.lastmodified ()). ToString (); }    }}

MyBatis Hot Load Mapper.xml

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.