Java and Hibernate date formatting

Asked

Viewed 1,507 times

0

Good morning, everyone! I am trying to return a formatted date, is in the database as date, but for return could be a string msm. Some friends have indicated two modes, either creating a new method for formatting or using java 1.8 Localdate.

The problem is that, as I am beginner and I end up lost in some things, I do not know how to return getFormatado... I will put the code that I think will explain better... I’m getting back with Hibernate....

package model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.ForeignKey;




@Entity
@Table(name ="fornecedor")
public class Fornecedor extends Pessoa{


@Column
private Integer codigo;
@Column
private String pessoaContato;
@Column
private String cnpj;
@Column
private Date inicioAtividades;

// ********* Omiti os Get and Setters desnecessários pra pergunta :)    

public Date getInicioAtividades() {
    return inicioAtividades;
}
public void setInicioAtividades(Date inicioAtividades) {
    this.inicioAtividades = inicioAtividades;
}


// ********** Pediram pra eu acrescentar este método aqui, abaixo

public String getInicioFormatado() throws ParseException { 
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String data = sdf.format(inicioAtividades);
    return data;
}

The problem is, how do I call this Kra, since in Hibernate is like this:

public List<Fornecedor> listarFornecedores() {
    session = HibernateUtil.getSessionFactory().openSession();
    List<Fornecedor> listaFornecedores = new ArrayList<Fornecedor>();
    query = session.createQuery("FROM Fornecedor");
    listaFornecedores = query.list();
    session.close();
    return listaFornecedores;

Can someone give me that light there? Personal thank you!!!

2 answers

0

I noticed that you did not use the temporal annotation provided in the Persistence 2.1 or later library that already comes bundled with Netbeans (I’m sorry about the confusion of terms, if any), in case you are using Eclipse I think you should download the library.

In this library we have 3 different notes:

  1. Temporaltype.DATE: This saves only the date part, in YYYY-MM-dd format
  2. Temporaltype.Time: This records only the time.
  3. Temporaltype.Timestamp: And this records the date and time, I can’t remember the format because I rarely use.

Example:

@javax.persistence.Entity
@Table(name = "fornecedor")
public class Fornecedor extends Pessoa {

private Integer codigo;

private String pessoaContato;

private String cnpj;

@Temporal(TemporalType.DATE)
private Date dataInicioAtividades;

@Temporal(TemporalType.TIME)
private Date horaInicioAtividades;

@Temporal(TemporalType.TIME)
private Date dataFimAtividades;

@Temporal(TemporalType.TIME)
private Date horafimAtividades;

//Getters and Setters
}

To save the date in one of the above formats just add the annotation @Temporal (parameter), and choose the format. You will replace in place of "parameter by desired type".

And in the date recovery it will already be in the preselected format, including it will be recorded in this format.

Ps: No need to add @Column annotations in all attributes, this annotation is usually used when the attribute name is different from the column name...

0

There are several ways you can map, which one you will use depends on the JPA/ORM version.

Starting with version 5.0, Hibernate now supports the Date and Time API of java 8. You simply add the dependency hibernate-java8 to your project:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-java8</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

As of version 5.2 the above dependency has been added to core hibernate and is no longer needed. In both cases your class would look like this:

@Entity
@Table(name ="fornecedor")
public class Fornecedor extends Pessoa{


    @Column
    private Integer codigo;
    @Column
    private String pessoaContato;
    @Column
    private String cnpj;
    @Column
    private LocalDate inicioAtividades;

    //...
    //Seus getters and setters normais, sem nenhuma conversão adicional
}

If you use a version earlier than 5.0 but this version supports JPA 2.1, you can use a AttributeConverter<X, Y>:

In this case, you should implement the following class:

public class LocalDateConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
    }

    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }
}

And change your supplier class to:

@Entity
@Table(name ="fornecedor")
public class Fornecedor extends Pessoa{


    @Column
    private Integer codigo;
    @Column
    private String pessoaContato;
    @Column
    private String cnpj;
    @Column
    @Convert(converter=LocalDateConverter.class)
    private LocalDate inicioAtividades;

    //...
    //Seus getters and setters normais, sem nenhuma conversão adicional
}

And lastly, you could do the conversions in your getters and setters:

@Entity
@Table(name ="fornecedor")
public class Fornecedor extends Pessoa{


    @Column
    private Integer codigo;
    @Column
    private String pessoaContato;
    @Column
    private String cnpj;
    @Transient
    private LocalDate inicioAtividades;

    public void setInicioAtividades(Date date) {
        inicioAtividades = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    @Column
    public Date getInicioAtividades() {
         Date.from(inicioAtividades.atStartOfDay(ZoneId.systemDefault()).toInstant()));
    }

    //...
    //Seus outros getters and setters 
}

For you to add a method that formats Localdate, just do this:

@Entity
@Table(name ="fornecedor")
public class Fornecedor extends Pessoa{

 //Seus outros campos e métodos

    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    public String getInicioAtividadesFormatado() {
         return inicioAtividades.format(DATE_FORMAT);
    }
}

Edit:

For you to call the getInicioAtividadesFormatado() just do this:

classX.listarFornecedores().forEach(f -> {
    String inicioAtividades = f.getInicioAtividadesFormatado();
    //Faça o que quiser aqui
});

Or if you want to search from the database only the inicioAtividades, you can do so:

public List<LocalDate> listarInicioAtividades() {
    session = HibernateUtil.getSessionFactory().openSession();
    List<LocalDate> listaInicioAtividades = new ArrayList<LocalDate>();
    query = session.createQuery("SELECT F.inicioAtividades FROM Fornecedor F");
    listaInicioAtividades = query.list();
    session.close();
    return listaInicioAtividades;

}

And to display the formatted list:

final DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
listarInicioAtividades().forEach(i -> {
    string dataFormatada = i.format(format);
    //Faça o que quiser aqui
});
  • Thanks for the reply, friend, it was very complete... but I still can not understand, it’s how I get the return of getInicioAtivitiesFormated, since there is no note of Hibernate and it is also not in the bank... I use Hibernate 5 :)

  • I edited the answer to show how to get the return.

  • Friend, Thank you. I will try here and after lunch I give an answer. Hug!

  • Sorry to keep you waiting. What I still can’t understand, is how I will do at the time when the select is run in Hibernate and the list is created, in which moment I call getInicioActivitiesFormated and I do the conversion, to enter the list in place of Homeactivities.

  • @So you want him to enter the village of inicioAtividades? I can’t imagine a scenario where that would be necessary. You could give the example of a situation where you think this should be done?

Browser other questions tagged

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