com.isea533.mybatis.mapperhelper.MapperHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.isea533.mybatis.mapperhelper.MapperHelper.java

Source

/*
   The MIT License (MIT)
    
   Copyright (c) 2014 abel533@gmail.com
    
   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:
    
   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.
    
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/

package com.isea533.mybatis.mapperhelper;

import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.builder.annotation.ProviderSqlSource;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.Method;
import java.util.*;

/**
 * ??
 * <p>? : <a href="https://github.com/abel533/Mapper" target="_blank">https://github.com/abel533/Mapper</a></p>
 *
 * @author liuzh
 */
public class MapperHelper {

    /**
     * Mapper?
     */
    private Map<Class<?>, MapperTemplate> registerMapper = new HashMap<Class<?>, MapperTemplate>();

    /**
     * msidMapperTemplate
     */
    private Map<String, MapperTemplate> msIdCache = new HashMap<String, MapperTemplate>();
    /**
     * skip
     */
    private final Map<String, Boolean> msIdSkip = new HashMap<String, Boolean>();

    /**
     * ??Collection<MappedStatement>
     */
    private Set<Collection<MappedStatement>> collectionSet = new HashSet<Collection<MappedStatement>>();

    /**
     * ?Spring
     */
    private boolean spring = false;

    /**
     * ?Spring4.x
     */
    private boolean spring4 = false;

    /**
     * Spring?
     */
    private String springVersion;

    /**
     * 
     */
    public MapperHelper() {
    }

    /**
     * ?
     *
     * @param properties
     */
    public MapperHelper(Properties properties) {
        setProperties(properties);
    }

    /**
     * ?SqlSession
     */
    private List<SqlSession> sqlSessions = new ArrayList<SqlSession>();

    /**
     * Spring??SqlSession
     *
     * @param sqlSessions
     */
    public void setSqlSessions(SqlSession[] sqlSessions) {
        if (sqlSessions != null && sqlSessions.length > 0) {
            this.sqlSessions.addAll(Arrays.asList(sqlSessions));
        }
    }

    /**
     * Spring?Spring??init-method="initMapper"
     */
    public void initMapper() {
        //?Spring,Spring?,???Spring
        //Spring,???
        //Spring4?,???Mapper
        initSpringVersion();
        for (SqlSession sqlSession : sqlSessions) {
            processConfiguration(sqlSession.getConfiguration());
        }
    }

    /**
     * Spring?,Spring4.x?
     */
    private void initSpringVersion() {
        try {
            //???SpringVersion
            Class<?> springVersionClass = Class.forName("org.springframework.core.SpringVersion");
            springVersion = (String) springVersionClass.getDeclaredMethod("getVersion", null).invoke(null, null);
            spring = true;
            if (springVersion.indexOf(".") > 0) {
                int MajorVersion = Integer.parseInt(springVersion.substring(0, springVersion.indexOf(".")));
                if (MajorVersion > 3) {
                    spring4 = true;
                } else {
                    spring4 = false;
                }
            }
        } catch (Exception e) {
            spring = false;
            spring4 = false;
        }
    }

    /**
     * ?Spring4.x
     *
     * @return
     */
    public boolean isSpring4() {
        return spring4;
    }

    /**
     * ?Spring4.x
     *
     * @return
     */
    public boolean isSpring() {
        return spring;
    }

    /**
     * ?Spring?
     *
     * @return
     */
    public String getSpringVersion() {
        return springVersion;
    }

    /**
     * Mapper??MapperTemplate
     *
     * @param mapperClass
     * @return
     * @throws Exception
     */
    private MapperTemplate fromMapperClass(Class<?> mapperClass) {
        Method[] methods = mapperClass.getDeclaredMethods();
        Class<?> templateClass = null;
        Class<?> tempClass = null;
        Set<String> methodSet = new HashSet<String>();
        for (Method method : methods) {
            if (method.isAnnotationPresent(SelectProvider.class)) {
                SelectProvider provider = method.getAnnotation(SelectProvider.class);
                tempClass = provider.type();
                methodSet.add(method.getName());
            } else if (method.isAnnotationPresent(InsertProvider.class)) {
                InsertProvider provider = method.getAnnotation(InsertProvider.class);
                tempClass = provider.type();
                methodSet.add(method.getName());
            } else if (method.isAnnotationPresent(DeleteProvider.class)) {
                DeleteProvider provider = method.getAnnotation(DeleteProvider.class);
                tempClass = provider.type();
                methodSet.add(method.getName());
            } else if (method.isAnnotationPresent(UpdateProvider.class)) {
                UpdateProvider provider = method.getAnnotation(UpdateProvider.class);
                tempClass = provider.type();
                methodSet.add(method.getName());
            }
            if (templateClass == null) {
                templateClass = tempClass;
            } else if (templateClass != tempClass) {
                throw new RuntimeException("Mapper??MapperTemplate?!");
            }
        }
        if (templateClass == null || !MapperTemplate.class.isAssignableFrom(templateClass)) {
            throw new RuntimeException(
                    "???typeMapperTemplateProvider??Mapper?!");
        }
        MapperTemplate mapperTemplate = null;
        try {
            mapperTemplate = (MapperTemplate) templateClass.getConstructor(Class.class, MapperHelper.class)
                    .newInstance(mapperClass, this);
        } catch (Exception e) {
            throw new RuntimeException("MapperTemplate:" + e.getMessage());
        }
        //
        for (String methodName : methodSet) {
            try {
                mapperTemplate.addMethodMap(methodName, templateClass.getMethod(methodName, MappedStatement.class));
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(templateClass.getCanonicalName() + "" + methodName + "!");
            }
        }
        return mapperTemplate;
    }

    /**
     * Mapper?
     *
     * @param mapperClass
     * @throws Exception
     */
    public void registerMapper(Class<?> mapperClass) {
        if (registerMapper.get(mapperClass) == null) {
            registerMapper.put(mapperClass, fromMapperClass(mapperClass));
        } else {
            throw new RuntimeException(
                    "?Mapper[" + mapperClass.getCanonicalName() + "]?!");
        }
    }

    /**
     * Mapper?
     *
     * @param mapperClass
     * @throws Exception
     */
    public void registerMapper(String mapperClass) {
        try {
            registerMapper(Class.forName(mapperClass));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Mapper[" + mapperClass + "]?Mapper!");
        }
    }

    /**
     * Spring
     *
     * @param mappers
     */
    public void setMappers(String[] mappers) {
        if (mappers != null && mappers.length > 0) {
            for (String mapper : mappers) {
                registerMapper(mapper);
            }
        }
    }

    /**
     * IDENTITY?
     */
    public enum IdentityDialect {
        DB2("VALUES IDENTITY_VAL_LOCAL()"), MYSQL("SELECT LAST_INSERT_ID()"), SQLSERVER(
                "SELECT SCOPE_IDENTITY()"), CLOUDSCAPE(
                        "VALUES IDENTITY_VAL_LOCAL()"), DERBY("VALUES IDENTITY_VAL_LOCAL()"), HSQLDB(
                                "CALL IDENTITY()"), SYBASE("SELECT @@IDENTITY"), DB2_MF(
                                        "SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1"), INFORMIX(
                                                "select dbinfo('sqlca.sqlerrd1') from systables where tabid=1");

        private String identityRetrievalStatement;

        private IdentityDialect(String identityRetrievalStatement) {
            this.identityRetrievalStatement = identityRetrievalStatement;
        }

        public String getIdentityRetrievalStatement() {
            return identityRetrievalStatement;
        }

        public static IdentityDialect getDatabaseDialect(String database) {
            IdentityDialect returnValue = null;
            if ("DB2".equalsIgnoreCase(database)) {
                returnValue = DB2;
            } else if ("MySQL".equalsIgnoreCase(database)) {
                returnValue = MYSQL;
            } else if ("SqlServer".equalsIgnoreCase(database)) {
                returnValue = SQLSERVER;
            } else if ("Cloudscape".equalsIgnoreCase(database)) {
                returnValue = CLOUDSCAPE;
            } else if ("Derby".equalsIgnoreCase(database)) {
                returnValue = DERBY;
            } else if ("HSQLDB".equalsIgnoreCase(database)) {
                returnValue = HSQLDB;
            } else if ("SYBASE".equalsIgnoreCase(database)) {
                returnValue = SYBASE;
            } else if ("DB2_MF".equalsIgnoreCase(database)) {
                returnValue = DB2_MF;
            } else if ("Informix".equalsIgnoreCase(database)) {
                returnValue = INFORMIX;
            }
            return returnValue;
        }
    }

    //??
    private class Config {
        private String UUID;
        private String IDENTITY;
        private boolean BEFORE = false;
        private String seqFormat;
        private String catalog;
        private String schema;
    }

    private Config config = new Config();

    /**
     * UUID
     *
     * @param UUID
     */
    public void setUUID(String UUID) {
        config.UUID = UUID;
    }

    /**
     * MYSQL
     *
     * @param IDENTITY
     */
    public void setIDENTITY(String IDENTITY) {
        IdentityDialect identityDialect = IdentityDialect.getDatabaseDialect(IDENTITY);
        if (identityDialect != null) {
            config.IDENTITY = identityDialect.getIdentityRetrievalStatement();
        } else {
            config.IDENTITY = IDENTITY;
        }
    }

    /**
     * selectKeyORDERAFTER
     *
     * @param order
     */
    public void setOrder(String order) {
        config.BEFORE = "BEFORE".equalsIgnoreCase(order);
    }

    /**
     * ??"{0}.nextval"
     *
     * @param seqFormat
     */
    public void setSeqFormat(String seqFormat) {
        config.seqFormat = seqFormat;
    }

    /**
     * catalog""
     *
     * @param catalog
     */
    public void setCatalog(String catalog) {
        config.catalog = catalog;
    }

    /**
     * schema""
     *
     * @param schema
     */
    public void setSchema(String schema) {
        config.schema = schema;
    }

    /**
     * ??catalogschema
     *
     * @return
     */
    public String getPrefix() {
        if (config.catalog != null && config.catalog.length() > 0) {
            return config.catalog;
        }
        if (config.schema != null && config.schema.length() > 0) {
            return config.catalog;
        }
        return "";
    }

    /**
     * ?UUID?
     *
     * @return
     */
    public String getUUID() {
        if (config.UUID != null && config.UUID.length() > 0) {
            return config.UUID;
        }
        return "@java.util.UUID@randomUUID().toString().replace(\"-\", \"\")";
    }

    /**
     * ?SQL
     *
     * @return
     */
    public String getIDENTITY() {
        if (config.IDENTITY != null && config.IDENTITY.length() > 0) {
            return config.IDENTITY;
        }
        //mysql
        return IdentityDialect.MYSQL.getIdentityRetrievalStatement();
    }

    /**
     * ?SelectKeyOrder
     *
     * @return
     */
    public boolean getBEFORE() {
        return config.BEFORE;
    }

    /**
     * ????
     *
     * @return
     */
    public String getSeqFormat() {
        if (config.seqFormat != null && config.seqFormat.length() > 0) {
            return config.seqFormat;
        }
        return "{0}.nextval";
    }

    /**
     * ???
     *
     * @param entityClass
     * @return
     */
    public String getTableName(Class<?> entityClass) {
        EntityHelper.EntityTable entityTable = EntityHelper.getEntityTable(entityClass);
        String prefix = entityTable.getPrefix();
        if (prefix.equals("")) {
            //?
            prefix = getPrefix();
        }
        if (!prefix.equals("")) {
            return prefix + "." + entityTable.getName();
        }
        return entityTable.getName();
    }

    /**
     * ????
     *
     * @param msId
     * @return
     */
    public boolean isMapperMethod(String msId) {
        if (msIdSkip.get(msId) != null) {
            return msIdSkip.get(msId);
        }
        for (Map.Entry<Class<?>, MapperTemplate> entry : registerMapper.entrySet()) {
            if (entry.getValue().supportMethod(msId)) {
                msIdSkip.put(msId, true);
                return true;
            }
        }
        msIdSkip.put(msId, false);
        return false;
    }

    /**
     * ?MapperTemplate
     *
     * @param msId
     * @return
     */
    private MapperTemplate getMapperTemplate(String msId) {
        MapperTemplate mapperTemplate = null;
        if (msIdCache.get(msId) != null) {
            mapperTemplate = msIdCache.get(msId);
        } else {
            for (Map.Entry<Class<?>, MapperTemplate> entry : registerMapper.entrySet()) {
                if (entry.getValue().supportMethod(msId)) {
                    mapperTemplate = entry.getValue();
                    break;
                }
            }
            msIdCache.put(msId, mapperTemplate);
        }
        return mapperTemplate;
    }

    /**
     * ?SqlSource
     *
     * @param ms
     */
    public void setSqlSource(MappedStatement ms) {
        MapperTemplate mapperTemplate = getMapperTemplate(ms.getId());
        try {
            if (mapperTemplate != null) {
                mapperTemplate.setSqlSource(ms);
            }
        } catch (Exception e) {
            throw new RuntimeException(":" + e.getMessage());
        }
    }

    /**
     * ?
     *
     * @param properties
     */
    public void setProperties(Properties properties) {
        if (properties == null) {
            return;
        }
        String UUID = properties.getProperty("UUID");
        if (UUID != null && UUID.length() > 0) {
            setUUID(UUID);
        }
        String IDENTITY = properties.getProperty("IDENTITY");
        if (IDENTITY != null && IDENTITY.length() > 0) {
            setIDENTITY(IDENTITY);
        }
        String seqFormat = properties.getProperty("seqFormat");
        if (seqFormat != null && seqFormat.length() > 0) {
            setSeqFormat(seqFormat);
        }
        String catalog = properties.getProperty("catalog");
        if (catalog != null && catalog.length() > 0) {
            setCatalog(catalog);
        }
        String schema = properties.getProperty("schema");
        if (schema != null && schema.length() > 0) {
            setSchema(schema);
        }
        String ORDER = properties.getProperty("ORDER");
        if (ORDER != null && ORDER.length() > 0) {
            setOrder(ORDER);
        }
        //?
        String mapper = properties.getProperty("mappers");
        if (mapper != null && mapper.length() > 0) {
            String[] mappers = mapper.split(",");
            for (String mapperClass : mappers) {
                if (mapperClass.length() > 0) {
                    registerMapper(mapperClass);
                }
            }
        }
    }

    /**
     * ?configurationMappedStatement
     *
     * @param configuration
     */
    public void processConfiguration(Configuration configuration) {
        Collection<MappedStatement> collection = configuration.getMappedStatements();
        //????
        if (collectionSet.contains(collection)) {
            return;
        } else {
            collectionSet.add(collection);
        }
        int size = collection.size();
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
            Object object = iterator.next();
            if (object instanceof MappedStatement) {
                MappedStatement ms = (MappedStatement) object;
                if (isMapperMethod(ms.getId())) {
                    if (ms.getSqlSource() instanceof ProviderSqlSource) {
                        setSqlSource(ms);
                    }
                }
            }
            //??selectKeyms??
            if (collection.size() != size) {
                size = collection.size();
                iterator = collection.iterator();
            }
        }
    }
}