org.apache.ibatis.session.SqlSessionFactory Java Examples
The following examples show how to use
org.apache.ibatis.session.SqlSessionFactory.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MybatisTest.java From code with Apache License 2.0 | 7 votes |
/** * 测试mybatis环境 */ public static void main(String[] args) throws Exception { // 1、读取配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 2、创建SqlSessionFactory的建造者 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); // 3、使用建造者创建工厂对象SqlSessionFactory SqlSessionFactory factory = builder.build(in); // 4、使用SqlSessionFactory创建SqlSession对象 SqlSession session = factory.openSession(); // 5、使用SqlSession创建dao接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); // 6、使用代理对象执行sql查询 System.out.println("基于XML配置"); userMapper.findAll().forEach(System.out::println); System.out.println("基于注解配置"); userMapper.findUsers().forEach(System.out::println); // 7、释放资源 session.close(); in.close(); }
Example #2
Source File: AutomaticLazyLoadingTest.java From mybatis with Apache License 2.0 | 6 votes |
/** * Create a session with the specified configuration and initialized the database. */ private void openSession(String aConfig) throws Exception { final String resource = "org/apache/ibatis/submitted/automatic_lazy_loading/ibatis-automatic-lazy-load-" + aConfig + ".xml"; Reader batisConfigReader = Resources.getResourceAsReader(resource); SqlSessionFactory sqlSessionFactory; try { sqlSessionFactory = new SqlSessionFactoryBuilder().build(batisConfigReader); } catch(Exception anException) { throw new RuntimeException("Mapper configuration failed, expected this to work: " + anException.getMessage(), anException); } SqlSession session = sqlSessionFactory.openSession(); Connection conn = session.getConnection(); ScriptRunner runner = new ScriptRunner(conn); runner.setLogWriter(null); runner.setErrorLogWriter(null); Reader createScriptReader = Resources.getResourceAsReader("org/apache/ibatis/submitted/automatic_lazy_loading/create.sql"); runner.runScript(createScriptReader); sqlSession = sqlSessionFactory.openSession(); }
Example #3
Source File: MybatisSessionInstance.java From SSO with Apache License 2.0 | 6 votes |
public static SqlSession getInstance() { if (sf == null) { synchronized (SqlSessionFactory.class) { if (sf == null) { try { Reader reader = Resources.getResourceAsReader(resource); sf = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } } } return sf.openSession(); }
Example #4
Source File: ApiBootMybatisPageableAutoConfiguration.java From beihu-boot with Apache License 2.0 | 6 votes |
/** * init interceptors */ @PostConstruct void addInterceptors() { Interceptor interceptor = new MyBatisExecutePageableInterceptor(); // set properties to interceptor interceptor.setProperties(myBatisPageableProperties.getProperties()); for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) { // pre addPreInterceptors(sqlSessionFactory); // mybatis pageable interceptor sqlSessionFactory.getConfiguration().addInterceptor(interceptor); // post addPostInterceptors(sqlSessionFactory); } }
Example #5
Source File: DatabaseConfig.java From SO with BSD 2-Clause "Simplified" License | 6 votes |
@Bean(name = "sqlSessionFactory") @Primary public SqlSessionFactory SqlSessionFactory(@Qualifier("datasource") DataSource dataSource , ApplicationContext applicationContext) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // accur Could not resolve type alias in running jar sqlSessionFactoryBean.setVfs(SpringBootVFS.class); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setMapperLocations( applicationContext.getResources("classpath:META-INF/mappers/*.xml") ); // configuration 은 xml 파일로 처리 sqlSessionFactoryBean.setConfigLocation( applicationContext.getResource("classpath:META-INF/mybatis-config.xml") ); // sqlSessionFactoryBean.setConfigurationProperties(mybatisProperties()); sqlSessionFactoryBean.setTypeAliasesPackage("com.pineone.icbms.so.interfaces.database.model"); return sqlSessionFactoryBean.getObject(); }
Example #6
Source File: RefCursorTest.java From mybatis with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Test public void testRefCursor2() throws IOException { Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/refcursor/MapperConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { OrdersMapper mapper = sqlSession.getMapper(OrdersMapper.class); Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("orderId", 1); mapper.getOrder2(parameter); assertNotNull(parameter.get("order")); List<Order> orders = (List<Order>) parameter.get("order"); assertEquals(1, orders.size()); Order order = orders.get(0); assertEquals(3, order.getDetailLines().size()); } finally { sqlSession.close(); } }
Example #7
Source File: ClusterDataSourceConfig.java From springBoot-study with Apache License 2.0 | 6 votes |
@Bean(name = "clusterSqlSessionFactory") public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(clusterDataSource); //分页插件 Interceptor interceptor = new PageInterceptor(); Properties properties = new Properties(); //数据库 properties.setProperty("helperDialect", "mysql"); //是否将参数offset作为PageNum使用 properties.setProperty("offsetAsPageNum", "true"); //是否进行count查询 properties.setProperty("rowBoundsWithCount", "true"); //是否分页合理化 properties.setProperty("reasonable", "false"); interceptor.setProperties(properties); sessionFactory.setPlugins(new Interceptor[] {interceptor}); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(ClusterDataSourceConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); }
Example #8
Source File: XmlExternalRefTest.java From mybatis with Apache License 2.0 | 6 votes |
private void testCrossReference(SqlSessionFactory sqlSessionFactory) throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); try { PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); Person person = personMapper.select(1); assertEquals((Integer)1, person.getId()); assertEquals(2, person.getPets().size()); assertEquals((Integer)2, person.getPets().get(1).getId()); Pet pet = personMapper.selectPet(1); assertEquals(Integer.valueOf(1), pet.getId()); PetMapper petMapper = sqlSession.getMapper(PetMapper.class); Pet pet2 = petMapper.select(3); assertEquals((Integer)3, pet2.getId()); assertEquals((Integer)2, pet2.getOwner().getId()); } finally { sqlSession.close(); } }
Example #9
Source File: InsertTest.java From mybaties with Apache License 2.0 | 6 votes |
@Test public void testInsertAnnotated() throws Exception { Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/keycolumn/MapperConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); try { InsertMapper mapper = sqlSession.getMapper(InsertMapper.class); Name name = new Name(); name.setFirstName("Fred"); name.setLastName("Flintstone"); int rows = mapper.insertNameAnnotated(name); assertNotNull(name.getId()); assertEquals(1, rows); } finally { sqlSession.close(); } }
Example #10
Source File: MybatisBatchUpdaters.java From sqlhelper with GNU Lesser General Public License v3.0 | 6 votes |
public static <E> MybatisBatchUpdater<E> createBatchUpdater(@NonNull SqlSessionFactory sessionFactory, @Nullable BatchMode batchType) { MybatisBatchUpdater<E> updater = null; if (batchType != null) { switch (batchType) { case SIMPLE: updater = new SimpleBatchUpdater<E>(); break; case BATCH_SQL: updater = new BatchSqlBatchUpdater<E>(); break; case JDBC_BATCH: updater = new JdbcBatchUpdater<E>(); break; default: break; } } if (Objects.isNotNull(updater)) { updater.setSessionFactory(sessionFactory); } return updater; }
Example #11
Source File: GjpaymentDatabaseConfig.java From maintain with MIT License | 6 votes |
@Bean(name = "gjpaymentSqlSessionFactory") public SqlSessionFactory gjpaymentSqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); logger.info("gjpayment sqlsession--" + this.gjpaymentDataSource().hashCode()); sqlSessionFactoryBean.setDataSource(this.gjpaymentDataSource()); PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("dialect", "oracle"); properties.setProperty("pageSizeZero", "true"); properties.setProperty("reasonable", "false"); properties.setProperty("params", "pageNum=pageHelperStart;pageSize=pageHelperRows;"); properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("returnPageInfo", "none"); pageHelper.setProperties(properties); Interceptor[] interceptors = new Interceptor[] { pageHelper }; sqlSessionFactoryBean.setPlugins(interceptors); return sqlSessionFactoryBean.getObject(); }
Example #12
Source File: Read1DruidDataSourceConfig.java From SpringBoot-Study with Apache License 2.0 | 6 votes |
/** * SqlSessionFactory配置 * * @return * @throws Exception */ @Bean(name = "read1SqlSessionFactory") public SqlSessionFactory read1SqlSessionFactory( @Qualifier("read1DataSource") DataSource dataSource ) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 配置mapper文件位置 sqlSessionFactoryBean.setMapperLocations(resolver.getResources(read1MapperLocations)); //配置分页插件 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("reasonable", "true"); properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("returnPageInfo", "check"); properties.setProperty("params", "count=countSql"); pageHelper.setProperties(properties); //设置插件 sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper}); return sqlSessionFactoryBean.getObject(); }
Example #13
Source File: DatabaseConfig.java From SO with BSD 2-Clause "Simplified" License | 6 votes |
@Bean(name = "sqlSessionFactory") @Primary public SqlSessionFactory SqlSessionFactory(@Qualifier("datasource") DataSource dataSource , ApplicationContext applicationContext) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // accur Could not resolve type alias in running jar sqlSessionFactoryBean.setVfs(SpringBootVFS.class); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setMapperLocations( applicationContext.getResources("classpath:META-INF/mappers/*.xml") ); // configuration 은 xml 파일로 처리 sqlSessionFactoryBean.setConfigLocation( applicationContext.getResource("classpath:META-INF/mybatis-config.xml") ); // sqlSessionFactoryBean.setConfigurationProperties(mybatisProperties()); sqlSessionFactoryBean.setTypeAliasesPackage("com.pineone.icbms.so.interfaces.database.model"); return sqlSessionFactoryBean.getObject(); }
Example #14
Source File: IncludeTest.java From mybatis with Apache License 2.0 | 6 votes |
@Test public void testIncludes() throws Exception { String resource = "org/apache/ibatis/submitted/includes/MapperConfig.xml"; Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlMapper = builder.build(reader); assertNotNull(sqlMapper); final SqlSession sqlSession = sqlMapper.openSession(); try { final Integer result = sqlSession.selectOne("org.apache.ibatis.submitted.includes.mapper.selectWithProperty"); Assert.assertEquals(Integer.valueOf(1), result); } finally { sqlSession.close(); } }
Example #15
Source File: SessionFactoryImpl.java From tephra with MIT License | 5 votes |
private SqlSessionFactory create(String key, Mode mode, DataSource dataSource, String[] mappers) { Environment environment = new Environment(key + "-" + mode.ordinal(), new JdbcTransactionFactory(), dataSource); Configuration configuration = new Configuration(environment); for (String mapper : mappers) configuration.addMappers(mapper); return builder.build(configuration); }
Example #16
Source File: SameIdTest.java From mybatis with Apache License 2.0 | 5 votes |
private SqlSessionFactory getSqlSessionFactoryJavaConfig() throws Exception { Class.forName("org.hsqldb.jdbcDriver"); Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:xmlextref", "sa", ""); initDb(c); Configuration configuration = new Configuration(); Environment environment = new Environment("development", new JdbcTransactionFactory(), new UnpooledDataSource( "org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:xmlextref", null)); configuration.setEnvironment(environment); configuration.addMapper(SameIdPersonMapper.class); configuration.addMapper(SameIdPetMapper.class); return new SqlSessionFactoryBuilder().build(configuration); }
Example #17
Source File: DatabaseConfiguration.java From flowable-engine with Apache License 2.0 | 5 votes |
@Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); String databaseType = initDatabaseType(dataSource); if (databaseType == null) { throw new FlowableException("couldn't deduct database type"); } try { Properties properties = new Properties(); properties.put("prefix", modelerAppProperties.getDataSourcePrefix()); properties.put("blobType", "BLOB"); properties.put("boolValue", "TRUE"); properties.load(this.getClass().getClassLoader().getResourceAsStream("org/flowable/db/properties/" + databaseType + ".properties")); sqlSessionFactoryBean.setConfigurationProperties(properties); sqlSessionFactoryBean .setMapperLocations(ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:/META-INF/modeler-mybatis-mappings/*.xml")); sqlSessionFactoryBean.afterPropertiesSet(); return sqlSessionFactoryBean.getObject(); } catch (Exception e) { throw new FlowableException("Could not create sqlSessionFactory", e); } }
Example #18
Source File: SpringAnnotationTest.java From Mapper with MIT License | 5 votes |
@Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); tk.mybatis.mapper.session.Configuration configuration = new tk.mybatis.mapper.session.Configuration(); configuration.setMapperHelper(new MapperHelper()); sessionFactory.setConfiguration(configuration); return sessionFactory.getObject(); }
Example #19
Source File: MybatisConfiguration.java From dk-foundation with GNU Lesser General Public License v2.1 | 5 votes |
@Bean @Resource @Override public SqlSessionFactory sqlSessionFactory(DataSource myBatisDataSource) throws Exception { logger.info("-------------------- sqlSessionFactory init ---------------------"); return super.sqlSessionFactory(myBatisDataSource); }
Example #20
Source File: SeataDataSourceAutoConfig.java From seata-samples with Apache License 2.0 | 5 votes |
/** * init mybatis sqlSessionFactory * @Param: dataSourceProxy datasource proxy * @Return: DataSourceProxy datasource proxy */ @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources("classpath*:/mapper/*.xml")); return factoryBean.getObject(); }
Example #21
Source File: XmlExternalRefTest.java From mybaties with Apache License 2.0 | 5 votes |
private SqlSessionFactory getSqlSessionFactoryJavaConfig() throws Exception { Class.forName("org.hsqldb.jdbcDriver"); Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:xmlextref", "sa", ""); initDb(c); Configuration configuration = new Configuration(); Environment environment = new Environment("development", new JdbcTransactionFactory(), new UnpooledDataSource( "org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:xmlextref", null)); configuration.setEnvironment(environment); configuration.addMapper(PersonMapper.class); configuration.addMapper(PetMapper.class); return new SqlSessionFactoryBuilder().build(configuration); }
Example #22
Source File: ShortNameTest.java From mybaties with Apache License 2.0 | 5 votes |
private Configuration getConfiguration() throws IOException { Reader configReader = Resources .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/MapperConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader); configReader.close(); return sqlSessionFactory.getConfiguration(); }
Example #23
Source File: MyBatisModule.java From hasor with Apache License 2.0 | 5 votes |
private static SingleProvider<SqlSessionFactory> defaultSessionFactory(final String sqlmapConfig) throws IOException { Objects.requireNonNull(sqlmapConfig, "sqlmapConfig is null."); ClassLoader loader = Thread.currentThread().getContextClassLoader(); Reader resourceAsReader = Resources.getResourceAsReader(loader, sqlmapConfig); final Reader reader = Objects.requireNonNull(resourceAsReader, "could not find resource '" + sqlmapConfig + "'"); return new SingleProvider<>(() -> new SqlSessionFactoryBuilder().build(reader)); }
Example #24
Source File: AuthorityDatabaseAutoConfiguration.java From zuihou-admin-boot with Apache License 2.0 | 5 votes |
@Bean(DATABASE_PREFIX + "SqlSessionTemplate") public SqlSessionTemplate getSqlSessionTemplate(@Qualifier(DATABASE_PREFIX + "SqlSessionFactory") SqlSessionFactory sqlSessionFactory) { ExecutorType executorType = this.properties.getExecutorType(); if (executorType != null) { return new SqlSessionTemplate(sqlSessionFactory, executorType); } else { return new SqlSessionTemplate(sqlSessionFactory); } }
Example #25
Source File: MysqlDataSource2Config.java From mySpringBoot with Apache License 2.0 | 5 votes |
@Bean(name = "secondSqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db2/*.xml"); sessionFactory.setMapperLocations(mapperLocations); return sessionFactory.getObject(); }
Example #26
Source File: SeataAutoConfig.java From demo-seata-springcloud with Apache License 2.0 | 5 votes |
/** * 初始化mybatis sqlSessionFactory * * @param dataSourceProxy * @return * @throws Exception * @author sly * @time 2019年6月11日 */ @Bean public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSourceProxy); factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); factoryBean.setTypeAliasesPackage("com.sly.seata.common.model"); factoryBean.setTransactionFactory(new JdbcTransactionFactory()); return factoryBean.getObject(); }
Example #27
Source File: MybatisCRUDTest.java From code with Apache License 2.0 | 5 votes |
@Before//在测试方法执行之前执行 public void init() throws Exception { //1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建构建者对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //3.创建 SqlSession 工厂对象 SqlSessionFactory factory = builder.build(in); //4.创建 SqlSession 对象 session = factory.openSession(); //5.创建 Dao 的代理对象 userMapper = session.getMapper(UserMapper.class); }
Example #28
Source File: MultipleReverseIncludeTest.java From mybatis with Apache License 2.0 | 5 votes |
private SqlSessionFactory getSqlSessionFactoryJavaConfig() throws Exception { Class.forName("org.hsqldb.jdbcDriver"); Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:xmlextref", "sa", ""); initDb(c); Configuration configuration = new Configuration(); Environment environment = new Environment("development", new JdbcTransactionFactory(), new UnpooledDataSource( "org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:xmlextref", null)); configuration.setEnvironment(environment); configuration.addMapper(MultipleReverseIncludePersonMapper.class); return new SqlSessionFactoryBuilder().build(configuration); }
Example #29
Source File: DemoDatabaseAutoConfiguration.java From zuihou-admin-cloud with Apache License 2.0 | 5 votes |
@Bean(DATABASE_PREFIX + "SqlSessionTemplate") public SqlSessionTemplate getSqlSessionTemplate(@Qualifier(DATABASE_PREFIX + "SqlSessionFactory") SqlSessionFactory sqlSessionFactory) { ExecutorType executorType = this.properties.getExecutorType(); if (executorType != null) { return new SqlSessionTemplate(sqlSessionFactory, executorType); } else { return new SqlSessionTemplate(sqlSessionFactory); } }
Example #30
Source File: SharedSqlSessionFactoryCfgTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test public void shouldNotReuseCachedSqlSessionIfNotConfigured() { final TestEngineCfg cfg = new TestEngineCfg(); SqlSessionFactory existingSessionFactory = mock(SqlSessionFactory.class); // given ProcessEngineConfigurationImpl.cachedSqlSessionFactory = existingSessionFactory; // if cfg.initSqlSessionFactory(); // then assertSame(existingSessionFactory, ProcessEngineConfigurationImpl.cachedSqlSessionFactory); assertNotSame(existingSessionFactory, cfg.getSqlSessionFactory()); }