boot分页-pagehelper+模糊查询+批量修改

pom依赖


      <!-- 分页插件 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.2.5</version>
    </dependency>
   <!-- 接口文档生成工具 -->
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger2</artifactId>
          <version>2.8.0</version>
      </dependency>
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.8.0</version>
      </dependency>

      <dependency>
          <groupId>cn.hutool</groupId>
          <artifactId>hutool-all</artifactId>
          <version>5.3.10</version>
      </dependency>

      <dependency>
          <groupId>org.json</groupId>
          <artifactId>json</artifactId>
          <version>20180813</version><!--注意:20160810版本不支持JSONArray-->
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-configuration-processor</artifactId>
          <optional>true</optional>
      </dependency>

yml配置


pagehelper:
  helper-dialect: mysql
  reasonable: false
  support-methods-arguments: true
  params: count=countSql

封装PageInfo


/**
 *  分页 数据结构
 */
public class PageInfo<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    //当前页
    private int pageNum;
    //每页的数量
    private int pageSize;
    //总记录数
    private long total;
    //总页数
    private int pages;
    //结果集
    private List<T> list;
    //是否为第一页
    private boolean isFirstPage = false;
    //是否为最后一页
    private boolean isLastPage = false;


    public PageInfo() {
    }
    /**
     * 包装Page对象
     *
     * @param list
     */
    public PageInfo(List<T> list) {
        if (list instanceof Page) {
            Page page = (Page) list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();

            this.pages = page.getPages();
            this.list = page;
            this.total = page.getTotal();
        } else if (list instanceof Collection) {
            this.pageNum = 1;
            this.pageSize = list.size();

            this.pages = 1;
            this.list = list;
            this.total = list.size();
        }
        if (list instanceof Collection) {
            //判断页面边界
            judgePageBoudary();
        }
    }
    /**
     * 判定页面边界
     */
    private void judgePageBoudary() {
        isFirstPage = pageNum == 1;
        isLastPage = pageNum == pages;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public boolean isIsFirstPage() {
        return isFirstPage;
    }

    public void setIsFirstPage(boolean isFirstPage) {
        this.isFirstPage = isFirstPage;
    }

    public boolean isIsLastPage() {
        return isLastPage;
    }

    public void setIsLastPage(boolean isLastPage) {
        this.isLastPage = isLastPage;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("PageInfo{");
        sb.append("pageNum=").append(pageNum);
        sb.append(", pageSize=").append(pageSize);
        sb.append(", total=").append(total);
        sb.append(", pages=").append(pages);
        sb.append(", list=").append(list);
        sb.append(", isFirstPage=").append(isFirstPage);
        sb.append(", isLastPage=").append(isLastPage);
        sb.append(", navigatepageNums=");
        sb.append('}');
        return sb.toString();
    }
}

API


@Api(tags = "模板管理")
public interface TemplateAdministrationControllerApi {

    @ApiOperation(value = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "zt", value = "状态:正常为:1,冻结为:2"),
            @ApiImplicitParam(name = "websiteName", value = "网站名称"),
            @ApiImplicitParam(name = "pageNum", value = "选填 第几页,默认第一页"),
            @ApiImplicitParam(name = "pageSize", value = "选填 每页条数,默认10条")

    })
    public ResultMap fandAll(@RequestParam(value = "zt", required = false) Integer zt,
                           @RequestParam(value = "websiteName", required = false) String websiteName,
                           @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    )
            throws MissingServletRequestParameterException;

    @ApiOperation(value = "添加&修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name=("idd"),value = "添加为1,修改 为2")
    })
    public ResultMap templateAdd(CrawlConfInfo crawlConfInfo,@RequestParam(value = "idd",required = true) int idd);

    @ApiOperation(value = "启用、禁用、删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name=("ids"),value = "id以:2,5,3"),
            @ApiImplicitParam(name=("lx"),value = "启用:1、禁用:2、删除:3")
    })
    public ResultMap switchs(@RequestParam(value = "ids",required = true) int ids[],@RequestParam(value = "lx",required = true) int lx);
}


controller


@RestController
@RequestMapping("/template")
public class TemplateAdministrationController implements TemplateAdministrationControllerApi {

    @Autowired
    TemplateAdministrationService templateAdministrationService;

    @GetMapping("/fandAll")
    public ResultMap fandAll(@RequestParam(value = "zt",required = false)Integer zt,
                           @RequestParam(value = "websiteName",required = false)String websiteName,
                           @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Page<CrawlConfInfo> result = templateAdministrationService.fandAll(zt,websiteName,pageNum,pageSize);
        PageInfo<CrawlConfInfo> objectPageInfo = new PageInfo<>(result);
        return new ResultMap(objectPageInfo);
    }


    @PostMapping("/templateAdd")
    public ResultMap templateAdd(CrawlConfInfo crawlConfInfo,int idd) {
        if(idd==1){
            templateAdministrationService.templateAdd(crawlConfInfo);
            return new ResultMap(200);
        }if (idd==2) {
            templateAdministrationService.save(crawlConfInfo);
            return new ResultMap(200);
        }
        return null;
    }

    @PostMapping("/switchs")
    public ResultMap switchs(int[] ids,int lx) {
        templateAdministrationService.switchs(ids,lx);
        return new ResultMap(200);
    }
}



@Service(value = "templateAdministrationService")
public class TemplateAdministrationServiceImpl implements TemplateAdministrationService {

  @Resource
  TemplateAdministrationDao templateAdministrationDao;
  
  @Override
  public Page<CrawlConfInfo> fandAll(Integer zt, String websiteName, int pageNum, Integer pageSize) {
      PageHelper.startPage(pageNum, pageSize);
      Page<CrawlConfInfo> all = templateAdministrationDao.findAll(zt, websiteName);
      return all;
  }

  @Override
  public CrawlConfInfo templateAdd(CrawlConfInfo crawlConfInfo) {
      CrawlConfInfo crawlConfInfo1 = templateAdministrationDao.templateAdd(crawlConfInfo);
      crawlConfInfo.setStatus(1);
      return crawlConfInfo1;
  }

  @Override
  public CrawlConfInfo save(CrawlConfInfo crawlConfInfo) {
      CrawlConfInfo save = templateAdministrationDao.save(crawlConfInfo);
      return save;
  }

  @Override
  public void switchs(int[] ids,int lx) {
      //启用
      if(lx==1){
          templateAdministrationDao.switchsStart(ids);
      }
      //禁用
      if(lx==2){
          templateAdministrationDao.switchsForbidden(ids);
      }
      //删除
      if(lx==3){
          templateAdministrationDao.switchsDel(ids);
      }
  }
}

DAO


@Mapper
public interface TemplateAdministrationDao {


    Page<CrawlConfInfo> findAll(Integer zt, String websiteName);

    CrawlConfInfo templateAdd(CrawlConfInfo crawlConfInfo);

    CrawlConfInfo save(CrawlConfInfo crawlConfInfo);

    void switchsStart(@Param("ids") int[] ids);

    void switchsForbidden(@Param("ids")int[] ids);

    void switchsDel(@Param("ids")int[] ids);
}

SQL


<mapper namespace="com.bonc.ygjq.backstage.collection.dao.TemplateAdministrationDao" >


    <select id="findAll" resultType="map">
        select  *  from crawl_conf_info
        <where>
        1=1
        <if test="zt != null">
          and  status=#{zt}
        </if>
        <if test="websiteName != null">
           and website_name like  concat('%',#{websiteName},'%')
        </if>
        </where>
    </select>

    <select id="templateAdd" parameterType="CrawlConfInfo">
        INSERT INTO `crawl_conf_info`(`conf_id`, `website_homepage_url`, `target_webpage_url`, `data_label`, `user_name`, `password`, `frequency`, `website_name`, `sucess_counts`, `target_token`, `creat_time`, `end_time`, `status`, `data_site`, `state_type`, `modify_time`, `trigger_time`)
        VALUES (null, #{websiteHomepageUrl}, #{targetWebpageUrl}, #{dataLabel}, #{userName}, #{password}, #{frequency}, #{websiteName}, #{sucessCounts}, #{targetToken}, #{creatTime}, #{endTime}, #{status}, #{dataSite}, #{stateType}, #{modifyTime}, #{triggerTime});
    </select>

    <select id="save" parameterType="CrawlConfInfo">
        UPDATE `crawl_conf_info`
        set website_homepage_url= #{websiteHomepageUrl},target_webpage_url= #{targetWebpageUrl},data_label= #{dataLabel},user_name= #{userName}, password= #{password},frequency= #{frequency},
       website_name=  #{websiteName},sucess_counts= #{sucessCounts},target_token= #{targetToken},creat_time= #{creatTime},end_time= #{endTime},status= #{status},data_site= #{dataSite},
       state_type= #{stateType},modify_time= #{modifyTime},trigger_time= #{triggerTime}
       WHERE `conf_id` = #{confId};
    </select>
<!--    启用-->
    <select id="switchsStart">
        update crawl_conf_info SET status=1
        <where>
            conf_id  IN
            <!--               ids传递过来的  item 相当于对象             , 分隔      -->
            <foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
                 ${item}
            </foreach>
        </where>
    </select>

<!--禁用-->
    <select id="switchsForbidden">
        update crawl_conf_info SET status=2
        <where>
            conf_id  IN
            <foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
                ${item}
            </foreach>
        </where>
    </select>
<!--删除-->
    <select id="switchsDel">
        update crawl_conf_info SET status=3
        <where>
            conf_id  IN
            <foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
                ${item}
            </foreach>
        </where>
    </select>

</mapper>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里是一个简单的 Spring-boot+Spring-batch+hibernate+Quartz 的批量读文件写数据的例子。 首先,需要在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 在 application.yml 文件中配置数据源和 Quartz: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true username: root password: root jpa: hibernate: ddl-auto: update show-sql: true quartz: job-store-type: jdbc jdbc: initialize-schema: always ``` 接下来,定义实体类 FileData: ```java @Entity @Table(name = "file_data") public class FileData { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "file_name") private String fileName; @Column(name = "line_number") private Integer lineNumber; @Column(name = "line_data") private String lineData; // getter and setter } ``` 定义读取文件的 ItemReader: ```java @Component @StepScope public class FileItemReader implements ItemReader<String> { private static final Logger LOGGER = LoggerFactory.getLogger(FileItemReader.class); private String file; private BufferedReader reader; @Value("#{jobParameters['file']}") public void setFile(String file) { this.file = file; } @BeforeStep public void beforeStep(StepExecution stepExecution) throws Exception { LOGGER.info("Starting to read file: {}", file); reader = new BufferedReader(new FileReader(file)); } @Override public String read() throws Exception { String line = reader.readLine(); if (line != null) { LOGGER.debug("Read line: {}", line); } else { LOGGER.info("Finished reading file: {}", file); reader.close(); } return line; } } ``` 定义处理数据的 ItemProcessor: ```java @Component public class FileItemProcessor implements ItemProcessor<String, FileData> { private static final Logger LOGGER = LoggerFactory.getLogger(FileItemProcessor.class); @Override public FileData process(String line) throws Exception { LOGGER.debug("Processing line: {}", line); String[] parts = line.split(","); FileData fileData = new FileData(); fileData.setFileName(parts[0]); fileData.setLineNumber(Integer.parseInt(parts[1])); fileData.setLineData(parts[2]); return fileData; } } ``` 定义写数据的 ItemWriter: ```java @Component public class FileItemWriter implements ItemWriter<FileData> { private static final Logger LOGGER = LoggerFactory.getLogger(FileItemWriter.class); @Autowired private EntityManager entityManager; @Override @Transactional public void write(List<? extends FileData> items) throws Exception { LOGGER.info("Writing {} items", items.size()); for (FileData item : items) { entityManager.persist(item); } entityManager.flush(); } } ``` 定义 Job: ```java @Configuration @EnableBatchProcessing public class BatchConfiguration { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private FileItemReader fileItemReader; @Autowired private FileItemProcessor fileItemProcessor; @Autowired private FileItemWriter fileItemWriter; @Bean public Job fileToDatabaseJob() { return jobBuilderFactory.get("fileToDatabaseJob") .incrementer(new RunIdIncrementer()) .start(step1()) .build(); } @Bean public Step step1() { return stepBuilderFactory.get("step1") .<String, FileData>chunk(10) .reader(fileItemReader) .processor(fileItemProcessor) .writer(fileItemWriter) .build(); } } ``` 定义 Quartz 定时任务: ```java @Component public class FileToDatabaseJobScheduler { @Autowired private SchedulerFactory schedulerFactory; @Autowired private JobDetail fileToDatabaseJobDetail; @Autowired private CronTriggerFactoryBean fileToDatabaseJobTrigger; @PostConstruct public void scheduleFileToDatabaseJob() throws SchedulerException { Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.scheduleJob(fileToDatabaseJobDetail, fileToDatabaseJobTrigger.getObject()); scheduler.start(); } } ``` 最后,启动应用程序并将文件作为参数传递: ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean @StepScope public FileItemReader fileItemReader(@Value("#{jobParameters['file']}") String file) { FileItemReader reader = new FileItemReader(); reader.setFile(file); return reader; } @Bean public JobDetail fileToDatabaseJobDetail() { return JobBuilder.newJob(BatchConfiguration.class) .withIdentity("fileToDatabaseJob") .storeDurably() .build(); } @Bean public CronTriggerFactoryBean fileToDatabaseJobTrigger(@Autowired JobDetail fileToDatabaseJobDetail) { CronTriggerFactoryBean trigger = new CronTriggerFactoryBean(); trigger.setJobDetail(fileToDatabaseJobDetail); trigger.setCronExpression("0 0/1 * 1/1 * ? *"); // 每分钟执行一次 return trigger; } } ``` 以上就是一个简单的 Spring-boot+Spring-batch+hibernate+Quartz 的批量读文件写数据的例子。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值