Example usage for org.apache.ibatis.io Resources getResourceAsStream

List of usage examples for org.apache.ibatis.io Resources getResourceAsStream

Introduction

In this page you can find the example usage for org.apache.ibatis.io Resources getResourceAsStream.

Prototype

public static InputStream getResourceAsStream(String resource) throws IOException 

Source Link

Document

Returns a resource on the classpath as a Stream object

Usage

From source file:PersistenceTest.java

License:Open Source License

public static SqlSessionFactory getSqlSessionFactory() {
    SqlSessionFactory sqlSessionFactory = null;
    if (sqlSessionFactory == null) {
        InputStream inputStream;/*w w w  . j a  va  2s  .  c  om*/
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config-h2.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e.getCause());
        }
    }
    return sqlSessionFactory;
}

From source file:cc.oit.dao.impl.mybatis.session.XMLConfigBuilder.java

License:Apache License

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
        for (XNode child : parent.getChildren()) {
            if ("package".equals(child.getName())) {
                String mapperPackage = child.getStringAttribute("name");
                configuration.addMappers(mapperPackage);
            } else {
                String resource = child.getStringAttribute("resource");
                String url = child.getStringAttribute("url");
                String mapperClass = child.getStringAttribute("class");
                if (resource != null && url == null && mapperClass == null) {
                    ErrorContext.instance().resource(resource);
                    InputStream inputStream = Resources.getResourceAsStream(resource);
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource,
                            configuration.getSqlFragments());
                    mapperParser.parse();
                } else if (resource == null && url != null && mapperClass == null) {
                    ErrorContext.instance().resource(url);
                    InputStream inputStream = Resources.getUrlAsStream(url);
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url,
                            configuration.getSqlFragments());
                    mapperParser.parse();
                } else if (resource == null && url == null && mapperClass != null) {
                    Class<?> mapperInterface = Resources.classForName(mapperClass);
                    configuration.addMapper(mapperInterface);
                } else {
                    throw new BuilderException(
                            "A mapper element may only specify a url, resource or class, but not more than one.");
                }// w w  w . j  a v a2  s. c om
            }
        }
    }
}

From source file:cn.com.bricks.mybatis.rbac.DynamicRbacInterceptorNGTest.java

/**
 * intercept (DynamicRbacInterceptor)/* w ww  .  j a v a 2 s . com*/
 */
@Test
public void testIntercept() throws Throwable {
    System.out.println("intercept");
    InputStream inputStream = null;
    try {

        inputStream = Resources.getResourceAsStream("cn/com/bricks/mybatis/test/MapperConfig.xml");
        SqlSessionManager sqlSession = SqlSessionManager.newInstance(inputStream);

        int count = sqlSession.openSession()
                .selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectCountOfPosts");
        System.out.println(count);
    } catch (IOException ex) {
        Logger.getLogger(DynamicRbacInterceptorNGTest.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            inputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(DynamicRbacInterceptorNGTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.baomidou.mybatisplus.MybatisXMLConfigBuilder.java

License:Apache License

private void mapperElement(XNode parent) throws Exception {
    /**/* ww w .j  a va 2  s  .  c  o m*/
     * ? ?mybatisMapperXML ????
     */
    if (parent != null) {
        //classpathmapper
        Set<String> resources = new HashSet<>();
        //?mapper?
        Set<Class<?>> mapperClasses = new HashSet<>();
        setResource(parent, resources, mapperClasses);
        // ???  resource ? mapper
        for (String resource : resources) {
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //TODO
            MybatisXMLMapperBuilder mapperParser = new MybatisXMLMapperBuilder(inputStream, configuration,
                    resource, configuration.getSqlFragments());
            mapperParser.parse();
        }
        for (Class<?> mapper : mapperClasses) {
            //TODO
            configuration.addMapper(mapper);
        }
    }
}

From source file:com.cetiti.dsp.builder.XMLMapperEntityResolver.java

License:Apache License

private InputSource getInputSource(String path, InputSource source) {
    if (path != null) {
        InputStream in;//from   ww  w . jav a 2s  .  c  o  m
        try {
            in = Resources.getResourceAsStream(path);
            source = new InputSource(in);
        } catch (IOException e) {
            // ignore, null is ok
        }
    }
    return source;
}

From source file:com.dvdprime.server.mobile.config.MyBatisConfig.java

License:Apache License

/**
 * MyBatis ?  Configuration? .//from   ww  w.  ja  v  a2 s  . c o  m
 * 
 * @return
 */
public Configuration getConfig() {
    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    Environment environment = new Environment("master", transactionFactory, getTomcatDataSource());

    logger.info("MyBatis Configuration Initialization.");
    Configuration configuration = new Configuration(environment);
    configuration.setCacheEnabled(true);
    configuration.setLazyLoadingEnabled(false);
    configuration.setAggressiveLazyLoading(false);
    configuration.setUseColumnLabel(true);
    configuration.setUseGeneratedKeys(false);
    configuration.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);
    configuration.setDefaultExecutorType(ExecutorType.REUSE);
    configuration.setDefaultStatementTimeout(25000);
    configuration.setSafeRowBoundsEnabled(true);

    // Alias Type
    Iterator<String> it = TypeAliasProp.getProperties().keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        logger.info("typeAliasRegistry: [{}] -> [{}]", key, TypeAliasProp.getProperties().get(key));
        configuration.getTypeAliasRegistry().registerAlias(key,
                (String) TypeAliasProp.getProperties().get(key));
    }

    // Mapper
    it = MapperProp.getProperties().keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        logger.info("mapper loaded: [{}]", MapperProp.getProperties().get(key));
        try {
            InputStream inputStream = Resources
                    .getResourceAsStream((String) MapperProp.getProperties().get(key));
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration,
                    (String) MapperProp.getProperties().get(key), configuration.getSqlFragments());
            mapperParser.parse();
        } catch (IOException e) {
            logger.error("mapper parsing   ?.");
        }
    }

    return configuration;
}

From source file:com.easyshop.common.mybatis.SqlSessionFactoryBean.java

License:Apache License

private void autoParse(Configuration configuration) throws IOException {
    String scanMappingResourceDir = this.baseScan;
    List<String> lists = new ArrayList<String>();
    String scanPath = scanMappingResourceDir + "/*"
            + ((null != this.suffix && this.suffix.trim().length() > 0) ? this.suffix.trim() : "") + ".xml";
    String realScanPathPattern = "classpath*:" + scanPath;
    ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
    Resource[] source = new Resource[0];
    try {/*from  w w w  . j a  va 2s .  c om*/
        source = resourceLoader.getResources(realScanPathPattern);
    } catch (IOException e) {
        logger.warn("[" + scanMappingResourceDir + "]XML?");
    }

    if (source.length == 0) {
        logger.warn("[" + scanMappingResourceDir + "]XML?");
        return;
    }

    for (int i = 0; i < source.length; i++) {
        Resource resource = source[i];
        lists.add(scanMappingResourceDir + "/" + resource.getFilename());
    }
    for (String resource : lists) {
        InputStream inputStream = Resources.getResourceAsStream(resource);
        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource,
                configuration.getSqlFragments());
        mapperParser.parse();
    }
}

From source file:com.itfsw.mybatis.generator.plugins.tools.DBHelper.java

License:Apache License

/**
 * ?//  w  w  w. j  av a2  s  . c o  m
 * @param resource
 * @throws SQLException
 * @throws IOException
 */
public static void createDB(String resource) throws SQLException, IOException {
    try (Statement statement = connection.createStatement();
            // ??sql
            InputStream inputStream = Resources.getResourceAsStream(resource);
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
        // ?sql?
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (!line.startsWith("--")) {
                sb.append(line).append("\n");
            }
        }
        statement.execute(sb.toString());

        dbLock = resource;
    }
}

From source file:com.itfsw.mybatis.generator.plugins.tools.DBHelper.java

License:Apache License

/**
 * ??/*from   w  ww  .  j a va2 s . com*/
 * @param resource
 * @throws SQLException
 * @throws IOException
 */
public static void resetDB(String resource) throws Exception {
    if (dbLock == null || !dbLock.equals(resource)) {
        throw new Exception("??????");
    }

    try (Statement statement = connection.createStatement();
            // ??sql
            InputStream inputStream = Resources.getResourceAsStream(resource);
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
        // ?sql?
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (!line.startsWith("--")) {
                sb.append(line).append("\n");

                if (line.matches(".*;$\\s*")) {
                    String sql = sb.toString().trim();

                    if (sql.startsWith("DROP")) {
                        statement.execute(sql.replace("DROP TABLE IF EXISTS", "TRUNCATE TABLE"));
                    } else if (!sql.startsWith("CREATE")) {
                        statement.execute(sql);
                    }

                    sb.setLength(0);
                }
            }
        }
    }
}

From source file:com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool.java

License:Apache License

/**
 * /*from   w  w  w .  jav a  2s.  c om*/
 * @param resource
 * @return
 */
public static MyBatisGeneratorTool create(String resource) throws IOException, XMLParserException {
    MyBatisGeneratorTool tool = new MyBatisGeneratorTool();
    tool.warnings = new ArrayList<>();

    // MyBatisGenerator 
    ConfigurationParser cp = new ConfigurationParser(tool.warnings);
    tool.config = cp.parseConfiguration(Resources.getResourceAsStream(resource));
    // ?
    tool.fixConfigToTarget();
    return tool;
}