0

I am working in users creation so, right now I need to order the list of active users sort by date, is to say the last updated user. I have a class that define my entity "Users" in my database, I am trying to store the full date (Year,Month,Day Hours, Minutes, Seconds, Nanosecons), but when I save the user in the table only is stored Year,Month,Day and the other attributes are "0". I am using Datetime as a data type in the table column, and Date in Java to map this entity. If someone can help me to find my error, or other solution to do it I will appreciated it. thanks a lot

This is my code:

@Entity
@Table(name = "users")....
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long user_id;
    
@Column(nullable = false)
private boolean is_active;

@Column(nullable = false)
private String created_by;

@Column
@Temporal(TemporalType.DATE)
private Date createdAt;

@Column(nullable = true)
private String updated_by;

@Column
@Temporal(TemporalType.DATE)
private Date updatedAt;

Implementation

Date date2 = java.util.Calendar.getInstance().getTime();  
newUser.setCreatedAt(date2);
newUser.setUpdatedAt(date2);
newUser = this.userRepository.save(newUser);

Result enter image description here

Claudia Bermúdez
  • 125
  • 1
  • 3
  • 11
  • You're using a `Date` in Java, which has no time portion. Consider `DateTime` or `ZonedDateTime` instead. – gvee Nov 18 '20 at 17:23
  • use Timestamp " java.sql.Timestamp" instead of Date – priyranjan Nov 18 '20 at 17:25
  • 1
    Actually the classes `java.until.Date`, `java.sql.Date`, `Calendar`, and `java.sql.Timestamp` are all terribly flawed in design. They were supplanted years ago by the modern *java.time* classes defined in JSR 310 with the approval of Sun, Oracle, and the JCP community. JPA and Hibernate both support *java.time*. There is no reason to ever use those awful legacy classes again. Search Stack Overflow as this has been addressed many many times already. – Basil Bourque Nov 18 '20 at 17:35
  • 2
    Would `@Temporal(TemporalType.DATE)` mean that only the date part should be saved? That said I too recommend that you neither use `java.util.Date`, `java.sql.Date` nor `java.sql.Timestamp`. Those classes are poorly designed and long outdated. Use `timestamp with time zone` in the database (or the SQL Server equivalent) and `OffsetDateTime` from java.time, the modern Java date and time API, in your Java program. – Ole V.V. Nov 18 '20 at 17:49
  • 1
    Yep, needs to be `TemporalType.TIMESTAMP` (**iff** using `java.util.Date`/`Calendar`), as well as all the considerations of the old classes vs. new classes and all that jazz. – Kayaman Nov 18 '20 at 17:53

0 Answers0