Spring Boot перезаписывает данные - PullRequest
0 голосов
/ 04 ноября 2019

Я пытаюсь прочитать файл .txt и сохранить его в своей базе данных при загрузке Spring.

Однако в каждом случае данные перезаписываются поверх одного и того же идентификатора. ,Идентификатор не увеличивается, даже если я установил @GeneratedValue (strategy = GenerationType.AUTO) в файле сущности.

Я ничего не нашел по этому поводу, и мне действительно нужно это выяснить.

Что такоепроблема?

public void resposta() throws IOException, ParseException {

    TableSap tableSap = new TableSap();



     File f=new File("C:\\Users\\carvalhog\\Desktop\\ResultadoIdoc.txt");     //Creation of File Descriptor for input file
     String[] words=null;  //Intialize the word Array
     FileReader fr = new FileReader(f);  //Creation of File Reader object
     BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object
     String s;     
     String[] dados;
     String input=" Ordem de venda  Organização de vendas       Canal de distribuição   Setor de atividade  Escritório de vendas    Equipe de vendas    Tipo de documento de vendas Criado em (data)    Vlr total ordem Emissor da ordem    Nome do emissor da ordem    Representante   Nome do representante";   // Input word to be searched
     int count=0;   //Intialize the word to zero


     while((s=br.readLine())!=null)   //Reading Content from the file
     {
        words=s.split("/n");  //Split the word using space
         for (String word : words) 
         {
                if(count>0)
                    count++;

                if (word.equals(input) && count==0)   //Search for the given word
                {
                  count=1;    //If Present increase the count by one
                }

                if(count>2) //Enter here after skipping previous lines preceding input variable
                {
                     dados=s.split("\t");

                     String replaceData = dados[9].replace(".", "/");
                     Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(replaceData);

                     String trim = dados[10].trim();
                     String replacevalue = trim.replace(".", "");
                     String replacevalue2 = replacevalue.replace(",", ".");

                     tableSap.setOrdem_vda(Long.parseLong(dados[1]));
                     tableSap.setOrg_vda(Long.parseLong(dados[2]));
                     tableSap.setCanal_dist(Long.parseLong(dados[4]));
                     tableSap.setSetor_ativ(Long.parseLong(dados[5]));
                     tableSap.setEscritorio((dados[6]));
                     tableSap.setEquipe((dados[7]));
                     tableSap.setTipo_doc((dados[8]));
                     tableSap.setCreate_data((date1));

                     try{
                     tableSap.setVlr_total_ordem(Double.parseDouble(replacevalue2));
                     } catch(NumberFormatException ex){ // handle your exception

                    }

                     tableSap.setEmissor_ordem(Long.parseLong(dados[11]));
                     tableSap.setNome_emissor((dados[12]));
                     tableSap.setRepr(Long.parseLong(dados[13]));
                     tableSap.setNome_repr((dados[14]));

                     sapService.save(tableSap); //Save each instance on DB
                }

         }

     }
        fr.close();
  }

TableSap Entity:

@Entity @Qualifier("kpi")
public class TableSap {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long ids;

@Column(name = "ordem_vda")
private Long ordem_vda;

@Column(name = "org_vda")
private Long org_vda;

@Column(name = "canal_dist")
private Long canal_dist;

@Column(name = "setor_ativ")
private Long setor_ativ;

@Column(name = "escritorio")
private String escritorio;

@Column(name = "equipe")
private String equipe;

@Column(name = "tipo_doc")
private String tipo_doc;

@Column(name = "create_data")
private Date create_data;

@Column(name = "vlr_total_ordem")
private Double vlr_total_ordem;

@Column(name = "emissor_ordem")
private Long emissor_ordem;

@Column(name = "nome_emissor")
private String nome_emissor;

@Column(name = "repr")
private Long repr;

@Column(name = "nome_repr")
private String nome_repr;

public TableSap() {
    super();
}

public Long getIds() {
    return ids;
}

public void setIds(Long ids) {
    this.ids = ids;
}

public Long getOrdem_vda() {
    return ordem_vda;
}

public void setOrdem_vda(Long ordem_vda) {
    this.ordem_vda = ordem_vda;
}

public Long getOrg_vda() {
    return org_vda;
}

public void setOrg_vda(Long org_vda) {
    this.org_vda = org_vda;
}

public Long getCanal_dist() {
    return canal_dist;
}

public void setCanal_dist(Long canal_dist) {
    this.canal_dist = canal_dist;
}

public Long getSetor_ativ() {
    return setor_ativ;
}

public void setSetor_ativ(Long setor_ativ) {
    this.setor_ativ = setor_ativ;
}

public String getEscritorio() {
    return escritorio;
}

public void setEscritorio(String escritorio) {
    this.escritorio = escritorio;
}

public String getEquipe() {
    return equipe;
}

public void setEquipe(String equipe) {
    this.equipe = equipe;
}

public String getTipo_doc() {
    return tipo_doc;
}

public void setTipo_doc(String tipo_doc) {
    this.tipo_doc = tipo_doc;
}

public Date getCreate_data() {
    return create_data;
}

public void setCreate_data(Date create_data) {
    this.create_data = create_data;
}

public Double getVlr_total_ordem() {
    return vlr_total_ordem;
}

public void setVlr_total_ordem(Double vlr_total_ordem) {
    this.vlr_total_ordem = vlr_total_ordem;
}

public Long getEmissor_ordem() {
    return emissor_ordem;
}

public void setEmissor_ordem(Long emissor_ordem) {
    this.emissor_ordem = emissor_ordem;
}

public String getNome_emissor() {
    return nome_emissor;
}

public void setNome_emissor(String nome_emissor) {
    this.nome_emissor = nome_emissor;
}

public Long getRepr() {
    return repr;
}

public void setRepr(Long repr) {
    this.repr = repr;
}

public String getNome_repr() {
    return nome_repr;
}

public void setNome_repr(String nome_repr) {
    this.nome_repr = nome_repr;
}

}

1 Ответ

0 голосов
/ 05 ноября 2019

Когда вы впервые сохраняете объект, его идентификатор равен null. Если вы используете Spring DATA JPA, его метод save распознает его и обрабатывает как новый объект, поэтому создайте для него новый идентификатор и сохраните как новый объект. (используя create) В следующий раз, когда вы сохраняете тот же самый объект , его идентификатор уже установлен, поэтому Spring DATA JPA предполагает, что вы хотите изменить его, поэтому он переопределит ту же самую запись DB (объединение). Либо создайте объект TableSap внутри цикла:

            if(count>2) 
            {
                 dados=s.split("\t");
                 TableSap tableSap = new TableSap();
                 ...

или сбросьте идентификатор на null, прежде чем использовать его повторно (хотя я голосую за первое решение):

            if(count>2) 
            {
                 dados=s.split("\t");
                 tableSap.setids(null);
                 ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...