grimlek grimlek - 4 months ago 54
Java Question

java.time YearMonth as a type within entity

How do you use YearMonth within an entity? I have seen a lot of stack overflow answers about a converter? Is this still needed and if so how?

@Basic(optional = false)
@Column(name = "cc_exp_date")
private YearMonth ccExpDate;

The exception I am getting is below. Could I just convert this into a date within the set method and convert back to YearMonth within the get method of the entity as a work around?

MysqlDataTruncation: Data truncation: Incorrect date value: '\xAC\xED\x00\x05sr\x00\x0Djava.time.Ser\x95]\x84\xBA\x1B"H\xB2\x0C\x00\x00xpw\x06\x0C\x00\x00\x07\xE2\x02x' for column 'cc_exp_date' at row 1


If your JPA provider does not persist a type in a sensible manner (in this case because it is a Java8 class, which was added after JPA 2.1 was approved, and because you're using EclipseLink which hasn't had much updates of late to support newer types) then you need to define a JPA 2.1 AttributeConverter to convert it to a standard JPA persistable type (in this case something like java.sql.Date).

Other JPA providers support persisting such types out of the box (DataNucleus JPA certainly does, and Hibernate also maybe with an optional dependency?)