/** * 根据数据源创建SqlSessionFactory */ @Bean public SqlSessionFactory sqlSessionFactory(AbstractRoutingDataSource routingDataSource) throws Exception { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(routingDataSource);// 指定数据源(这个必须有,否则报错) // 下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加 factoryBean.setTypeAliasesPackage("com.tangcheng.datasources.aop.model");// 指定基包 factoryBean.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));// return factoryBean.getObject(); }
/** * 循环标签 测试 */ public static void main(String[] args) { // 加载配置文件 InputStream in = CircularLabelsTest.class.getClassLoader().getResourceAsStream("mysql-config.xml"); MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder(); SqlSessionFactory sessionFactory = mf.build(in); SqlSession session = sessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); Page<User> page = new Page<>(1, 6); List<User> users = userMapper.forSelect(page, Arrays.asList("1", "2", "3")); System.out.println(users.toString()); System.out.println(page); User user = new User(); user.setId(1L); User users1 = userMapper.selectOne(user); System.out.println(users1); TestMapper mapper = session.getMapper(TestMapper.class); Test test = new Test(); test.setCreateTime(new Date()); test.setType("11111"); mapper.insert(test); session.rollback(); }
/** * <p> * 事务测试 * </p> */ public static void main(String[] args) { /* * 加载配置文件 */ InputStream in = TransactionalTest.class.getClassLoader().getResourceAsStream("mysql-config.xml"); MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder(); SqlSessionFactory sessionFactory = mf.build(in); SqlSession sqlSession = sessionFactory.openSession(); /** * 插入 */ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int rlt = userMapper.insert(new User(IdWorker.getId(), "1", 1, 1)); System.err.println("--------- insertInjector --------- " + rlt); //session.commit(); sqlSession.rollback(); sqlSession.close(); }
public static void main(String[] args) { /* * 加载配置文件 */ InputStream in = NoXMLTest.class.getClassLoader().getResourceAsStream("mysql-config.xml"); MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder(); SqlSessionFactory sessionFactory = mf.build(in); SqlSession sqlSession = sessionFactory.openSession(); /** * 查询是否有结果 */ TestMapper testMapper = sqlSession.getMapper(TestMapper.class); testMapper.insert(new Test(IdWorker.getId(), "Caratacus")); List<Map<String, Object>> list = testMapper.selectMaps(null); List<Map<String, Object>> list1 = testMapper.selectMapsPage(RowBounds.DEFAULT, null); List<Map<String, Object>> list2 = testMapper.selectMapsPage(new Page<>(1, 5), null); System.out.println(list); System.out.println(list1); System.out.println(list2); testMapper.delete(null); }
@Bean @ConditionalOnMissingBean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(roundRobinDataSouceProxy()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml")); sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); return sqlSessionFactoryBean.getObject(); }
/** * Get SQL session by environment name, create a new session if requested environment is not found * * @param environmentName * @return SqlSessionFactory */ @Override public SqlSessionFactory getSqlSessionFactory(String environmentName) { if (StringUtils.isBlank(environmentName) || sessionFactories.containsKey(environmentName)) { return sessionFactories.get(environmentName); } //implement double check locking so that we're protected against multiple threads trying to get a session //factory while avoiding the possibility of duplication session factories and not hurting performance for 99% of //the calls. synchronized (this) { if (StringUtils.isBlank(environmentName) || sessionFactories.containsKey(environmentName)) { return sessionFactories.get(environmentName); } else { return buildSessionFactory(dataSourceFactories.get(environmentName), environmentName); } } }
@Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); //mybatis分页 PageHelper pageHelper = new PageHelper(); Properties props = new Properties(); props.setProperty("dialect", "mysql"); props.setProperty("reasonable", "true"); props.setProperty("supportMethodsArguments", "true"); props.setProperty("returnPageInfo", "check"); props.setProperty("params", "count=countSql"); pageHelper.setProperties(props); //添加插件 sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper}); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/me/caixin/dao/mapping/**/*.xml")); return sqlSessionFactoryBean.getObject(); }
@Bean(name="sqlSessionFactory") @ConditionalOnMissingBean public SqlSessionFactory sqlSessionFactory() { try { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setTypeAliasesPackage(typeAliasesPackage); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sessionFactory.setMapperLocations(resolver.getResources(mapperLocations)); PageInterceptor pageInterceptor = new MysqlPageInterceptor(); sessionFactory.setPlugins(new Interceptor[]{pageInterceptor}); return sessionFactory.getObject(); } catch (Exception e) { logger.warn("Could not confiure mybatis session factory", e); return null; } }
/** * Dynamic sql session factory sql session factory. * * @param dynamicDataSource the dynamic data source * @param properties the properties * @return the sql session factory */ @Bean @ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX) public SqlSessionFactory dynamicSqlSessionFactory( @Qualifier("dynamicDataSource") DataSource dynamicDataSource, MybatisProperties properties) { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dynamicDataSource); sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(properties.getConfigLocation())); sessionFactory.setMapperLocations(properties.resolveMapperLocations()); try { return sessionFactory.getObject(); } catch (Exception e) { throw new SystemException(e); } }
/** * This method creates the sqlSessionManager of myBatis. It integrates all the SQL mappers * * @return a {@link SqlSessionFactory} */ private SqlSessionManager createSqlSessionManager() { Environment environment = new Environment(DEFAULT, this.transactionFactory, taskanaEngineConfiguration.getDatasource()); Configuration configuration = new Configuration(environment); // add mappers configuration.addMapper(TaskMapper.class); configuration.addMapper(TaskMonitorMapper.class); configuration.addMapper(WorkbasketMapper.class); configuration.addMapper(DistributionTargetMapper.class); configuration.addMapper(ClassificationMapper.class); configuration.addMapper(WorkbasketAccessMapper.class); configuration.addMapper(ObjectReferenceMapper.class); configuration.addMapper(QueryMapper.class); configuration.addMapper(AttachmentMapper.class); configuration.getTypeHandlerRegistry().register(MapTypeHandler.class); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(configuration); SqlSessionManager sessionManager = SqlSessionManager.newInstance(sessionFactory); return sessionManager; }
/** * SqlSessionFactory配置 * * @return * @throws Exception */ @Bean(name = "read2SqlSessionFactory") public SqlSessionFactory read2SqlSessionFactory( @Qualifier("read2DataSource") DataSource dataSource ) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 配置mapper文件位置 sqlSessionFactoryBean.setMapperLocations(resolver.getResources(read2MapperLocations)); //配置分页插件 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(); }
/** * SqlSessionFactory配置 * * @return * @throws Exception */ @Bean(name = "masterSqlSessionFactory") @Primary public SqlSessionFactory masterSqlSessionFactory( @Qualifier("masterDataSource") DataSource dataSource ) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 配置mapper文件位置 sqlSessionFactoryBean.setMapperLocations(resolver.getResources(masterMapperLocations)); //配置分页插件 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(); }
/** * SqlSessionFactory配置 * * @return * @throws Exception */ @Bean(name = "cluster1SqlSessionFactory") public SqlSessionFactory cluster1SqlSessionFactory( @Qualifier("cluster1DataSource") DataSource dataSource ) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //配置mapper文件位置 sqlSessionFactoryBean.setMapperLocations(resolver.getResources(cluster1MapperLocations)); //配置分页插件 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(); }
/** * 获取SqlSession * @return * @throws IOException */ public SqlSession getSqlSession() throws IOException, ClassNotFoundException { org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration(); config.setCallSettersOnNulls(true); // 设计null调用setter方法 config.setMapUnderscoreToCamelCase(true); // 驼峰命名支持 // 设置mapper config.addMappers(targetPackage); // 设置数据源,事务 PooledDataSourceFactory dataSourceFactory = new PooledDataSourceFactory(); dataSourceFactory.setProperties(DBHelper.properties); DataSource dataSource = dataSourceFactory.getDataSource(); JdbcTransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("test", transactionFactory, dataSource); config.setEnvironment(environment); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config); return sqlSessionFactory.openSession(true); }
@Bean @ConditionalOnMissingBean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { ExecutorType executorType = this.properties.getExecutorType(); if (executorType != null) { return new SqlSessionTemplate(sqlSessionFactory, executorType); } else { return new SqlSessionTemplate(sqlSessionFactory); } }
public static SqlSessionFactory getSqlSessionFactory() { try { Reader reader = getReader(); SqlSessionFactory sessionFactory = sqlSessionFactoryBuilderHolder.sqlSessionFactoryBuilder.build(reader); return sessionFactory; } catch (IOException e) { throw new RuntimeException("Exception in getSqlSessionFactory", e); } }
private void run() { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(getMySQLDataSource()); //SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(getH2DataSource()); try (SqlSession session = sqlSessionFactory.openSession(false)) { UsersDAO dao = session.getMapper(UsersDAO.class); createTableIfNotExists(dao); dao.save(new UsersDataSet("tully")); session.commit(); UsersDataSet dataSet = dao.select("tully"); System.out.println(dataSet); } }
/** * see com.baomidou.mybatisplus.spring.MybatisMapperRefresh#MybatisMapperRefresh(org.apache.ibatis.session.SqlSessionFactory, boolean) * * @param mapperLocations * @param sqlSessionFactory */ @Deprecated public MybatisMapperRefresh(Resource[] mapperLocations, SqlSessionFactory sqlSessionFactory) { this.mapperLocations = mapperLocations.clone(); this.sqlSessionFactory = sqlSessionFactory; this.configuration = sqlSessionFactory.getConfiguration(); this.run(); }
@Bean(name = "clusterSqlSessionFactory") public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(clusterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(ClusterDataSourceConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); }
public static void main(String[] args) throws IOException { Reader reader = Resources.getResourceAsReader("config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); try (SqlSession session = sqlSessionFactory.openSession(false)) { session.insert("ru.otus.mybatis.insert", new UsersDataSet(1,"deadbeaf")); session.commit(); UsersDataSet dataSet = session.selectOne("ru.otus.mybatis.select", "deadbeaf"); System.out.println(dataSet); } }
@Override public SqlSessionFactory build(Reader reader, String environment, Properties properties) { try { MybatisXMLConfigBuilder parser = new MybatisXMLConfigBuilder(reader, environment, properties); GlobalConfigUtils.setGlobalConfig(parser.getConfiguration(), this.globalConfig); return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); IOUtils.closeQuietly(reader); } }
@Override public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { try { MybatisXMLConfigBuilder parser = new MybatisXMLConfigBuilder(inputStream, environment, properties); GlobalConfigUtils.setGlobalConfig(parser.getConfiguration(), this.globalConfig); return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); IOUtils.closeQuietly(inputStream); } }
/** * 测试 Mybatis XML 修改自动刷新 */ public static void main(String[] args) throws IOException, InterruptedException { InputStream in = UserMapperTest.class.getClassLoader().getResourceAsStream("mysql-config.xml"); MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder(); mf.setGlobalConfig(new GlobalConfiguration(new MySqlInjector())); Resource[] resource = new ClassPathResource[]{new ClassPathResource("mysql/UserMapper.xml")}; SqlSessionFactory sessionFactory = mf.build(in); new MybatisMapperRefresh(resource, sessionFactory, 0, 5); boolean isReturn = false; SqlSession session = null; while (!isReturn) { try { session = sessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); userMapper.selectListRow(new Pagination(1, 10)); resource[0].getFile().setLastModified(SystemClock.now()); session.commit(); session.close(); Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } finally { if (session != null) { session.close(); } Thread.sleep(5000); } } System.exit(0); }
private SqlSessionFactory getSqlSessionFactory(DataSource dataSource) { TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); Configuration configuration = new Configuration(environment); configuration.addMapper(UsersDAO.class); return new SqlSessionFactoryBuilder().build(configuration); }
private void run() { // SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(getCustomDataSource()); SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(getH2DataSource()); try (SqlSession session = sqlSessionFactory.openSession(false)) { UsersDAO dao = session.getMapper(UsersDAO.class); createTableIfNotExists(dao); dao.save(new UsersDataSet("deadbeaf")); session.commit(); UsersDataSet dataSet = dao.select("deadbeaf"); System.out.println(dataSet); } }
@Bean public SqlSessionFactory sqlSessionFactory ( DynamicMultipleDataSource dynamicMultipleDataSource ) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource( dynamicMultipleDataSource ); return sqlSessionFactoryBean.getObject(); }
@Bean(name = "test2dbSqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("test2db") DataSource dataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setTypeAliasesPackage("com.maxplus1.demo.entity"); factoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:mapper/test2db/*.xml")); return factoryBean.getObject(); }
@Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactoryBean() { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setTypeAliasesPackage(ProjectConstant.MODEL_PACKAGE); //分页插件 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("pageSizeZero", "true");//分页尺寸为0时查询所有纪录不再执行分页 properties.setProperty("reasonable", "true");//页码<=0 查询第一页,页码>=总页数查询最后一页 properties.setProperty("supportMethodsArguments", "true");//支持通过 Mapper 接口参数来传递分页参数 properties.setProperty("returnPageInfo", "check"); // properties.setProperty("params", "count=countSql"); pageHelper.setProperties(properties); //添加插件 bean.setPlugins(new Interceptor[]{pageHelper}); //添加XML目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { bean.setMapperLocations(resolver.getResources("classpath*:mapper/*Mapper.xml")); return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
@Bean(name = "courseSqlSessionFactory") @Primary public SqlSessionFactory courseSqlSessionFactory(@Qualifier("courseDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); }
@Override protected SqlSessionFactory buildSqlSessionFactory() throws IOException { try { return super.buildSqlSessionFactory(); } catch (NestedIOException e) { logger.error("mapper.xml解析报错:",e); throw new NestedIOException("Failed to parse mapping resource: ", e); } finally { ErrorContext.instance().reset(); } }
/** * Sets the up. * * @throws Exception the exception */ @BeforeClass public static void setUp() throws Exception { System.out.println("Starting up CIMapper tests"); String resource = "mybatis-config.xml"; Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(reader); session = sf.openSession(); ciMapper = session.getMapper(CIMapper.class); }
@Bean(name = "studentSqlSessionFactory") public SqlSessionFactory studentSqlSessionFactory(@Qualifier("studentDataSource") DataSource studentDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(studentDataSource); return sessionFactory.getObject(); }
@SuppressWarnings("unused") private static void testState(SqlSessionFactory sqlsf) { SqlSession session = sqlsf.openSession(); DJMapper djMapper = session.getMapper(DJMapper.class); try { Integer stateId = djMapper.getReleaseStateId("qqqq"); } finally { session.close(); } }
@Bean(name = "mainSqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("mainDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/main/*.xml")); return bean.getObject(); }
@Bean(name = "masterSqlSessionFactory") @Primary public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception{ final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(masterDataSource); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MasterDataSourceConfig.MAPPER_LOCATION)); return sqlSessionFactoryBean.getObject(); }