0
I searched several places and did not find an answer, because it just doesn’t work by putting the annotations @Onetomany and @Manytoone, already put with fetch, with Mapped, didn’t work.
1 - How JPA relates two classes?
@Entity
public class Usuario {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name ="id")
private Long codigoUsuario;
private String nome;
@Column(unique = true)
@NotNull
private String cpf;
@NotNull
private String dataNascimento;
//@JoinColumn(name="id")
//@Transient
@OneToMany(mappedBy = "usuario")
private List<Endereco> list;
public List<Endereco> getList() {
return list;
}
@Entity
public class Endereco {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name ="endereco_id")
private Long id;
private String logradouro;
@NotNull
private String bairro;
@NotNull
private String cidade;
@NotNull
private String estado;
@NotNull
private String cep;
@ManyToOne
@JoinColumn(name = "codigoUsuario")
private Usuario usuario;
public Usuario getUsuario() {
return usuario;
}
2 - It is mandatory to create a query to relate the address list to the user class?
3 - As I update the address list, with a specific user, this is correct, if I go through POSTMAN?
{
"nome":"Rosana da Silva",
"email":"[email protected]",
"cpf":"5557059",
"dataNascimento": "14-12-1998",
"endereco":[{"id":611}]
}
@PostMapping("/usuario")
@ResponseStatus(value = HttpStatus.CREATED, reason = "Usuário cadastrado")
public Usuario salvaUsuario(@RequestBody Usuario usuario){
try {
return usuarioService.salvaUsuario(usuario);
} catch (Exception e){
throw new UsuarioInvalidoException("Cadastro inválido");
}
}