How to Recover Data from a Datepicket Add to Mysql/JPA Database

Asked

Viewed 80 times

1

I am trying to recover the data from a Datepicker in JAVAFX and put in my database, but I cannot convert in a certain way :(

    // Desse modo dá certo
    String cpf = cadastro_alunoCPF.getText();
    aluno.setNome(cadastro_alunoNome.getText());


   // Tentei por esse metodo mas não deu certo
   // LocalDate value = cadastro_alunoDataNasc.getValue();
   // aluno.setDataNasc(value);

DatePicket

2 answers

1


I managed to simply putting:

 LocalDate localDate = aluno_data_nasc.getValue();
 java.sql.Date sqlDate = java.sql.Date.valueOf(localDate);
 aluno.setDataNasc(sqlDate);

Thus returning the date of type "dd-mm-yy" as SQL supports

0

According to this source, JPA 2.1 does not natively support the new Date and Time API introduced with Java 8.

The author’s explanation is as follows:

The Answer is simple, JPA 2.1 was Released before Java 8 and the Date and Time API Simply didn’t exist at that point in time. Therefore the @Temporal Annotation can only be Applied to Attributes of type java.util.Date and java.util.Calendar.

The solution presented by the same source above is to use the Attributeconverter (credits to the author)

import java.sql.Date;
import java.time.LocalDate;

@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate locDate) {
        return locDate == null ? null : Date.valueOf(locDate);
    }

    @Override
    public LocalDate convertToEntityAttribute(Date sqlDate) {
        return sqlDate == null ? null : sqlDate.toLocalDate();
    }
}

Any additional problems I suggest reading the full article for more information.

Other sources: https://blog.tecsinapse.com.br/usando-localdate-java-8-no-hibernate4-jpa-2-1-972c463a44f9

Browser other questions tagged

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