Boa noite!
Estou com erro ao tentar gerar FK com Hibernate, ele não reconhece como FK e dá erro de registro duplicados.
Tenho uma classe Pessoa e uma classe Peso, a pessoa pode ter muitos pesos.
Classe Pessoa
@Entity
public class Pessoa {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotNull
@NotEmpty
private String nome;
@NotNull
@DateTimeFormat(iso = ISO.DATE)
@Past
private Calendar dataNascimento;
@Digits(integer = 1, fraction = 2)
private double altura;
@OneToOne
private Usuario usuario;
@NotNull
@NotEmpty
private String sexo;
Classe Peso
@Entity
public class Peso {
@ManyToOne
@NotNull
private Pessoa pessoa;
@Id
@DateTimeFormat(iso = ISO.DATE, pattern = "yyyy-MM-dd")
private Calendar data;
@NotNull
private double peso;
@NotNull
private double imc;
PesoController
@Transactional
@RequestMapping("registraPeso")
public String registraPeso(@Valid Peso peso, BindingResult result, @RequestParam("idPessoa") long idPessoa) {
System.out.println(peso.getData());
Pessoa pessoa = pessoaDao.findOne(idPessoa);
peso.setPessoa(pessoa);
pesoDao.save(peso);
return "redirect:meusDados";
}
Erro:
mar 24, 2020 10:29:24 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/controledepeso] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '2020-03-01 03:00:00' for key 'peso.PRIMARY'
O erro ocorre quanto eu tento inserir o peso para outra pessoa, porém numa data que já existe. No caso tentei inserir para a pessoa id 2.
Tabela
mysql> select * from peso;
+---------------------+-------+------+-----------+
| data | imc | peso | pessoa_id |
+---------------------+-------+------+-----------+
| 2020-03-01 03:00:00 | 24.51 | 70 | 1 |
| 2020-03-02 03:00:00 | 25.21 | 72 | 1 |
| 2020-03-03 03:00:00 | 23.81 | 68 | 1 |
+---------------------+-------+------+-----------+