简体   繁体   中英

Persist time with hibernate and java

(Spring app - MVC) I defined a table with the column:

`time` TIME NOT NULL,

In the entity class I have:

@Getter @Setter
@NotNull
private java.sql.Time time;

In my DTO class, I have:

@Getter @Setter
private java.sql.Time time;

When I send "time": "12:10" from postman I get: com.fasterxml.jackson.databind.JsonMappingException: Instantiation of [simple type, class java.sql.Time] value failed: null (through reference chain: (<points to a field (of java.sql.Time) in my aforementioned DTO class>))

When I have TIMESTAMP in MySQL, java LocalTime in both dto and entity, then it works but it persists both time and date. I would like to have time only.

I walked through different previous topics fe Joda-Time-Hibernate so I used LocalTime (in both dto and entity) with annotation @Type(type="org.joda.time.contrib.hibernate.PersistentLocalTimeAsTime") but it didn't work.

Could someone help me, what are the right types (time only) for dto, entity, table's column, so jackson can serialize, hibernate understand and persist.

As for serialization, you have to add this to your application.properties

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

this way you will allow simple date form mapping (Java8 requirement)

What I am using to store LocatDate as birthday

Dependecy:

compile('org.hibernate:hibernate-java8:5.0.12.Final')

In entity class

@Column
private LocalDate birthday;

No additional configuration required. What do I get in the database:

在此处输入图片说明

and the birthday is of type date

在此处输入图片说明

To have date and time I use Instant

@Data
@MappedSuperclass
public abstract class TimestampedEntity extends AbstractEntity {

    @Column(updatable = false)
    @Setter(value = AccessLevel.PRIVATE)
    private Instant createdAt;

    @Column
    @Setter(value = AccessLevel.PRIVATE)
    private Instant modifiedAt;

    @PrePersist
    private void beforeCreation() {
        this.setCreatedAt(Instant.now());
    }

    @PreUpdate
    private void beforeUpdate() {
        this.setModifiedAt(Instant.now());
    }

}

and this persists as Timestamp in database.

PS. I am using Spring+JPA+Hibernate+MySQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM