空值需要通过 POJO 类在 Mongo DB 中显示

Posted

技术标签:

【中文标题】空值需要通过 POJO 类在 Mongo DB 中显示【英文标题】:Null values needs to be displayed in Mongo DB through POJO class 【发布时间】:2021-09-07 00:01:13 【问题描述】:

我有一个基于 Spring Boot 框架编写的 Spring 批处理应用程序,它用于从 oracle 数据库(使用 JDBCcursorItemreader)读取数据并写入 Mongo 数据库(MongoItemWriter)。对于每个表,我都有一个 POJO 类。 mongo 集合中不显示空值字段。默认情况下,省略空值列的序列化会省略并仅显示非空列。

是否有任何其他属性可以在 mongo DB 中包含空字段?

例如:Oracle 表

Mongo 收藏:


"Name":"xyz",
"Number":"16"

想要以下格式:


"Name":"xyz",
"Number":"16",
"Date" : null

我想在 mongo DB 中显示日期列。我已尝试使用 jsoninclude 属性。它不起作用。有人可以就此提出建议吗?

我的代码: 批处理文件:

package com.sam.oracletomongo;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.job.flow.support.SimpleFlow;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.partition.PartitionHandler;
import org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler;
import org.springframework.batch.item.data.MongoItemWriter;
import org.springframework.batch.item.data.builder.MongoItemWriterBuilder;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.batch.item.database.support.ListPreparedStatementSetter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.mongodb.core.MongoTemplate;

@Configuration
@EnableBatchProcessing
@Import(AdditionalBatchConfiguration.class)
public class BABatchConfig  
    @Autowired
    public DataSource datasource;
    @Autowired
    public MongoTemplate mongotemplate;     
    
     @Autowired
        public JobBuilderFactory jobBuilderFactory;
        @Autowired
        public StepBuilderFactory stepBuilderFactory;
        @Bean
        @StepScope
        public JdbcCursorItemReader<BA> itemReaderBA(@Value("#jobParameters[deltadate]") String deltadate,@Value("#jobParameters[rundate]") String rundate) 
            ListPreparedStatementSetter listPreparedStatementSetter = new ListPreparedStatementSetter();    
            List<String> l1=new ArrayList<String>();
            l1.add(deltadate);
            l1.add(rundate);
            listPreparedStatementSetter.setParameters(l1);
            return new JdbcCursorItemReaderBuilder<BA>()
                .dataSource(datasource) // change accordingly if you use another data source
                .name("fooReader")
                .sql("SELECT SA_NO,SA_NAME,DATE1,DATE2,DATE3,ACTIVE FROM SAMPLE WHERE DATE2 between TO_DATE(?,'YYYY-MM-DD') and TO_DATE(?, 'YYYY-MM-DD')")
                .rowMapper(new BARowMapper())
                .preparedStatementSetter(listPreparedStatementSetter)
                .build();
                       
        @Bean
        public MongoItemWriter<BA> writerBA(MongoTemplate mongoTemplate) 
            
            
            return new MongoItemWriterBuilder<BA>().template(mongoTemplate).collection("BA")
                    .build();
        

       
    
        @Bean
public Job BAJob() 
            
            return jobBuilderFactory.get("BA")
                    .incrementer(new CustomParametersIncrementerImpl(datasource))
                    .start(BAstep())    
                    .build();
        
        
        @Bean
        public Step BAstep() 
            return stepBuilderFactory.get("BAStep1")
                    .<BA, BA> chunk(10)
                    .reader(itemReaderBA(null,null))                    
                    .writer(writerBA(mongotemplate))

                    .build();
        
       

            
      


Model Class:




package com.sam.oracletomongo;

public class BA 

private String _id;
private String saNo;
private String saName;
private String Date1;
private String Date2;
private String Date3;
private String active;

public String get_id() 
    return _id;

public void set_id(String _id) 
    this._id = _id;

public String getsaNo() 
    return saNo;

public void setBaNo(String saNo) 
    this.saNo = saNo;

public String getsaName() 
    return saName;

public void setBaName(String saName) 
    this.saName = saName;

public String getDate1() 
    return Date1;

public void setDate1(String Date1) 
    this.Date1 = Date1;

public String getDate2() 
    return Date2;

public void setDate2(String Date2) 
    this.Date2 = Date2;

public String getDate3() 
    return Date3;

public void setDate3(String Date3) 
    this.Date3 = Date3;

public String getActive() 
    return active;

public void setActive(String active) 
    this.active = active;

@Override
public String toString() 
    return "BA [_id=" + _id + ", saNo=" + saNo + ", saName=" + saName + ", Date1=" + Date1 + ", Date2="
            + Date2 + ", Date3=" + Date3 + ", active=" + active + "]";



映射器类:

package com.sam.oracletomongo;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

public class BARowMapper implements RowMapper<BA>   
         
    public BA mapRow(ResultSet rs, int rowNum) throws SQLException 
      
            BA ba = new BA();
            String id=rs.getString("sA_NO");
            ba.set_id(id); 
            ba.setsaNo(rs.getString("sA_NO"));
            ba.setsaName(rs.getString("sA_NAME"));
            ba.setDate1(rs.getString("DATE1"));
            ba.setDate2(rs.getString("DATE2"));
            ba.setDate3(rs.getString("DATE3"));
            ba.setActive(rs.getString("ACTIVE"));
            return ba;  
      
        

【问题讨论】:

使用$project 聚合的管道阶段并将$isNull 用于您要投影的密钥,如果您要查找的密钥不存在,则为null。如果您有示例代码,请告诉我 这能回答你的问题吗? Spring Data mongo to insert null values to DB 【参考方案1】:

这个$project 舞台可以帮助你:

  
    "$project": 
      _id: 0,
      "name": 1,
      "number": 1,
      "Date": 
        "$ifNull": [
          "$Date", //If the Date field is not null
          "null" //If the Date field is null write string 'null' to the field
        ]
      
    
  

【讨论】:

我不确定在哪里使用上面的 sn-p 和我的 POJO 类在 mongoitemwriter 将数据写入 MongoDB 期间自动转换为文档。请根据我的代码提出建议。 我也不确定,我以前从未使用过 Pojo,但肯定有一个可以编写聚合阶段的系统。如果你在那里调整这个阶段,它会起作用。

以上是关于空值需要通过 POJO 类在 Mongo DB 中显示的主要内容,如果未能解决你的问题,请参考以下文章

通过 R 连接时无法在 mongo DB 中查看集合

保留空值——Java POJO 到 org.JSONObject

获取空值,$sum 聚合 - Mongo

防止插入Mongo集合的数组中的空值

通过 rails 向 mongo 用户授予角色

Mongo - 忽略属性被持久化