简体   繁体   中英

JPA AttributeConverter is being ignored

I am trying to use an AttributeConverter to store the new Java 8 ZonedDateTime values in a MySQL database (DATETIME field) using Hibernate 4.3.0.

When I try to execute an update I get this error:

...Data truncation: Incorrect datetime value: '\xAC\xED\x00\x05sr\x00\x0Djava.time.Ser\x95]\x84\xBA\x1B"H\xB2\x0C\x00\x00xpw\x0D\x06\x00\x00\x07\xE0\x02\x11\x0B&\xEE\xE0\x08\x' for column...

I have read many SO answers saying to use the converter approach, so I wrote one:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Date;
import java.time.LocalDate;
import java.time.ZonedDateTime;

@Converter(autoApply = true)
public class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, Date> {
    @Override
    public Date convertToDatabaseColumn(ZonedDateTime zonedDateTime) {
        if (zonedDateTime == null) return null;

        return java.sql.Date.valueOf(zonedDateTime.toLocalDate());
    }

    @Override
    public ZonedDateTime convertToEntityAttribute(Date date) {
        if (date == null) return null;

        LocalDate localDate = date.toLocalDate();
        return ZonedDateTime.from(localDate);
    }
}

... but it never gets called.

I have even added jpaProperties.put("hibernate.archive.autodetection", "class, hbm"); to my jpaProperties, but no luck. The ZonedDateTimeConverter class is in the same package as my Entities, so it should get scanned.

What am I missing here?

Reading JPA 2.1 spec :

"The conversion of all basic types is supported except for the following: Id attributes (including the attributes of embedded ids and derived identities), version attributes, relationship attributes, and attributes explicitly annotated as Enumerated or Temporal or designated as such in the XML descriptor."

any chance your ZonedDateTime field is annotated with @Id or @Temporal in your entity ?

OK, this was my mistake. Part of my application is managed by Hibernate, but part of it is NOT. The object I'm having problems with is NOT managed by Hibernate, so it makes sense that the JPA stuff isn't getting called.

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