Date Formatting in Java and Hibernate

0

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

The problem is that since I'm a beginner and I get lost in some things, I do not know how to do it to return getFormatado ... I'm going through the code that I think will explain better ... I'm having a return 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 it looks 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 anyone give me this light there? Thank you guys!!!

    
asked by anonymous 16.01.2017 / 11:38

2 answers

0

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

From version 5.0 Hibernate is now able to support the Date and Time API of java 8. Just add the hibernate-java8 pendent dependency 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 of Hibernate and is no longer required. 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 prior to 5.0 but this version supports JPA 2.1, you can use 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 vendor 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 getInicioAtividadesFormatado() just do this:

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

Or if you want to fetch from the database only inicioAtividades , you can do this:

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
});
    
16.01.2017 / 12:39
0

I noticed that you did not use the temporary annotation provided in the Persistence 2.1 or later library that comes with NetBeans (I'm sorry for the confusion of terms, if any), in case you're using Eclipse I think you should the library.

In this library we have 3 different annotations:

  • TemporalType.DATE : This writes only the part of the date, in the format YYYY-MM-dd
  • TemporalType.Time : This records only the time.
  • TemporalType.TimeStamp : And this saves the date and time, I can not remember the format because I rarely use it.
  • 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
    }
    

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

    And in the recovery of the date it will already be in the pre-selected format, and it will be recorded in that format.

    Ps : It is not necessary to add the @Column annotations on all attributes, this annotation is generally used when the attribute name is different from the column name. .

        
    27.11.2018 / 18:25