Hibernate, JPA, does not save the new data in the database

Asked

Viewed 692 times

0

I have a Java Spring MVC application, with Hibernate and JPA and HTML interface.

I have two forms that depend on the Notebooks class and its attributes.

In the first form I enter the data of a new Notebook, saved in the database and a new ID is created for this record.

When I do a search, in the numeroID=44 case, the second form is displayed, which comes with some fields of the first form already filled, but disabled, and additional fields of the Notebook class enabled for editing. That is, in this second form I will only add more information to the same record that was added by the first form:

The problem is that when I click on the "Save" button of the second form, it does not save the new data entered in the second form in the database.

Class Notebooks Registered.

@Entity public class Notebooks Documents Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Long numeroID;
private String numeroCaderno;
private String cras;
private String dataRecebido;
private String recebidoPor;
private String avaliadoPor;
@Column(length = 2000)
private String observacoes;
private String codigoFamiliar;
private String nis;
private String data;
private String cpf;
private String rg;
private String ctps;
private String caixa;
private String cadernos;
private String certidaoNascimento;
private String fichaExclusao;
private String fichaAveriguacao;
private String suplementar;
private String suplementarDois;
private String entrevistador;
private String responsavelFamiliar;
private String pendenciaDocumentacao;
private String pendenciaFormulario;
private String pendenciaAssinatura;  
public String status;

Method change that is triggered by clicking the "Save" button of the second form:

@RequestMapping("alterar")
public String alterar(CadernosCadastrados objeto, Long numeroID, Model model) {

    List<CadernosCadastrados> cadernos = daoCadernosCadastrados.listar();

    daoCadernosCadastrados.alterar(objeto);
    //if(daoCadernosCadastrados.limpar(objeto )) {; 


    return "public/sucessos";

}

Change method in the Daocadernocanced class, which is called by the change method I showed earlier:

public void alterar(CadernosCadastrados objeto) {

    entityManager.merge(objeto);

}

2 answers

1

Your code is very confusing, let’s start with the service "change", in it you make a if (objeto.equals(objeto)), That doesn’t make any sense, you’re comparing something to itself, so I recommend removing that line or putting a validation that makes sense. Just below you call a listing that does nothing List<Caderno> cadernos = dao.listar();. Then we see an implementation of your DAO with a method that changes your notebook object, in it you take as parameter the class Caderno and has a if that will always be false because you always pass the id as null, for it is as follows Integer id = null; if (id != null)....

  • Adriano, so if this obejto.equals, I do it because I have an attribute in the Notebook class called "Status" it is like String, there is not be I pass it to Boolean, so this if, this List I do is to call the list of entered data, Already in the DAO I had to put this null, because as I put ID, no find he asked me to iniciliazar the only option was null, since I am not passing the parameter id, no change, because if I do not create a variable with id and not initialize it, no way is wrong, already the IF with id != null is to take out the nullpointer, got it.

0


I would use a Jparepository Extendo<>. Example of the class I made:

@Repository
public interface PessoaFisicaRepository extends JpaRepository<PessoaFisica, Long> {

}

And in service I did:

@Service
public class PessoaFisicaService {

          ** vários outros métodos **

     public PessoaFisica atualizar(PessoaFisica pessoaFisicaJson) {

            PessoaFisica pessoaFisicaBD = buscar(pessoaFisicaJson.getId());
            try {
                atualizarDados(pessoaFisicaBD, pessoaFisicaJson);
                pessoaFisicaBD = pessoaFisicaRepository.save(pessoaFisicaBD);
            } catch (DataIntegrityViolationException erro) {
                throw new ExcecaoDeIntegridadeDeDados("A integridade dos dados fornecidos estão corrompidos e/ou repetidos. Por favor, verifique-os e tente novamente");
            }
            return pessoaFisicaBD;
        }

     private void atualizarDados(PessoaFisica pessoaFisicaBD, PessoaFisica pessoaFisicaJson) {

            if (pessoaFisicaJson.getNome() != null) {
                pessoaFisicaBD.setNome(pessoaFisicaJson.getNome());
            }
            **outros métodos**
    }

     public PessoaFisica converteDeDto(PessoaFisicaDto pessoaFisicaDto) {

     PessoaFisica pessoaFisica = new PessoaFisica(pessoaFisicaDto.getAtivo(), pessoaFisicaDto.getIdEmpresa().. outros getters e setters

}

And finally in my Source:

@RestController
@RequestMapping(value = "/api/clientes/pf")
public class PessoaFisicaResource {
@PutMapping(value = "/{id}")
    public ResponseEntity<Void> atualizar(@Valid @RequestBody PessoaFisicaDto pessoaFisicaDto, @PathVariable Long id) {
        PessoaFisica pessoaFisica = pessoaFisicaService.converteDeDto(pessoaFisicaDto);
        pessoaFisica.setId(id);
        pessoaFisica = pessoaFisicaService.atualizar(pessoaFisica);
        return ResponseEntity.noContent().build();
    }
}

My DTO

@Getter  // lombok
@Setter  //lombok
public class PessoaFisicaDto implements Serializable {
private Long id;
@NotNull(message = "O campo ativo é obrigatório")
@Min(value = 0, message = "Digite 0 para inativo ou 1 para ativo")
@Max(value = 1, message = "Digite 0 para inativo ou 1 para ativo")
private Byte ativo;
@NotNull(message = "O campo id empresa é obrigatório")
   **vários outros atributos

}

How does it work? Send a JSON to the defined endpoint, in this case: /api/clients/pf/{id} The Resource handles the request, transforming DTO into Model, with the converted method DTO. Then he calls the atulizing method and finally builds the responseEntity.

  • Dude... doing everything in your hand is from the Stone Age. Or Maven or Radle. Study one of the two, or if you already know, go with the one that is easiest. I use both, but prefer Maven for personal reasons. To create spring applications, use https://start.spring.io/

  • Great news. I didn’t send anything because I’m very busy at the company.

  • I managed to solve, what I did I took the data of the first form and brought in the second form with the most filled out disabled data I changed in the change method that was with persist, to merge, so the ID was not changed and so saved the new data. in the same ID.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.