springboot定时操作数据库

工作中很多地方都需要使用定时器这个方法,比如定时操作数据库,定时更新等等。
java中有定时器的方法,比较麻烦,springboot中直接用注解就能实现。下面看如何实现

//一定要加上Service注解,否则无法找到这个方法

@Service
public class mapperTest {
    @Autowired
    private  testMapper mapper;
    @Scheduled(cron = "0/5 * * * * *")
    public void mes(){
        System.out.println("你好");
    }

//在你需要调用的方法上面加上这个注解,现在意思是20秒执行一次
    @Scheduled(cron = "0/20 * * * * *")
    public  void state() throws Exception{
    
//调用mapper中的方法
        List<String> mes = mapper.getMes();
        for (int i = 0; i <mes.size() ; i++) {

            System.out.println(mes.get(i));
        }

    }




下面看一下mapper中的方法

@Mapper
public interface testMapper {

    public List<String> getMes();
}

也很简单,注意加上mapper这个注解。mapper调用xml中的sql。再看一下xml中sql怎么写。

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.module.dao.testMapper">
   <select id="getMes" resultType="String">
       select  * from  test
   </select>
   
</mapper>

namespace就是你的mapper全类名,id就是mapper中的方法resultType是输出参数类型。

在配置文件中配置你的参数
也就是application.properties

spring.datasource.url=jdbc:mysql:/***。***.***.**:3306/test?useSSL=false&characterEncoding=utf8&allowMultiQueries=true&useUnicode=true
spring.datasource.username=root
#
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml

最后在启动类上加上开启注解的方法。

@EnableScheduling
@SpringBootApplication
//@MapperScan("com.example.demo.module.dao.testMapper")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

mapperscan是扫描你的mapper包的,可以加,也可以不加,结果都是一样的,他会自动去查找你的mapper。

好了,可以去测试了,可以看到控制台打印出了查询数据库的结果。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值