flink:从数据库取出数据,将计算出的数据存入到另一个表中

public class CaculateAvgAge {

    public static void main(String[] args) {

        //创建env
        ExecutionEnvironment enviroment = ExecutionEnvironment.getExecutionEnvironment();
//读取spring.xml配置
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/spring.xml");
        
        //getBean
        AverageService averageServiceImpl = applicationContext.getBean(AverageService.class);

        //sql
        String sql = "select id,name,age from user";

        //创建数据源
        JDBCInputFormat jdbcInputFormat = JDBCInputFormat.buildJDBCInputFormat()
                .setDBUrl("jdbc:mysql://localhost:3306/veronica")
                .setDrivername("com.mysql.jdbc.Driver")
                .setUsername("root")
                .setPassword("123456")
                .setRowTypeInfo(new RowTypeInfo(Types.INT, Types.STRING, Types.DOUBLE))
                .setQuery(sql)
                .finish();
                
        //读取数据源
        DataSource<Row> rowDataSource = enviroment.createInput(jdbcInputFormat).setParallelism(1);
        MapOperator<Row, User> mapOperator = rowDataSource.map(new RichMapFunction<Row, User>() {
            private AverageAccumulator averageAccumulator;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                //注册计算器(计算平均数)
                averageAccumulator = new AverageAccumulator();
                getRuntimeContext().addAccumulator("age", averageAccumulator);
            }

            @Override
            public User map(Row row) throws Exception {
                User user = new User();
                user.setId((int) row.getField(0));
                user.setName((String) row.getField(1));
                user.setAge((int)row.getField(2));
                averageAccumulator.add(user.getAge());
                return user;
            }
        });
        mapOperator.writeAsText("./avg", FileSystem.WriteMode.OVERWRITE);
        JobExecutionResult jobExecutionResult = null;
        try {
            jobExecutionResult = enviroment.execute("计算平均年龄");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Object count = jobExecutionResult.getAccumulatorResult("age");
       //将计算出来的年龄的平均值存入到average表中
        Average average = new Average();
        average.setAvgAge((Double) count);
        average.setAvgScore(111.11);
        averageServiceImpl.save(average);
       
    }
}

spring.xml配置

 <!-- 配置自动扫描的包,使其自动注入到IOC容器 -->
    <context:component-scan base-package="com.yyq"></context:component-scan>

    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:application.properties"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${spring.datasource.driver-class-name}"></property>
        <property name="url" value="${spring.datasource.url}"></property>
        <property name="username" value="${spring.datasource.username}"></property>
        <property name="password" value="${spring.datasource.password}"/>

        <property name="initialSize" value="1"/>
        <property name="maxActive" value="10"/>
    </bean>
    <!-- 配置MyBatis的SqlSession -->
    <bean id="sqlSessionFactory"
          class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBatis的配置的文件 -->
        <property name="configLocation" value="classpath:mybatis.xml"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
        <property name="typeAliasesPackage" value="com.yyq.repository.entity"></property>
        <!-- 别名处理 -->
        <!-- <property name="typeAliasesPackage" value="com.imooc.entity"></property> -->

        <!-- 插件注册 -->
        <property name="plugins">
            <list>
                <!-- 注册分页插件 -->
                <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></bean>
            </list>
        </property>

    </bean>


    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 自动扫描 com.imooc.dao下的interface,并加入IOC容器 -->
        <property name="basePackage" value="com.yyq.repository.dao"/>

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>


    <!-- 开启事务 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!-- 可通过注解控制事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>


在这里插入图片描述

在利用easymode生成mapper.xml的时候一定要注意namespace和resultMap,需要修改成对应的com.xxxx.

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值