如何将日期字符串作为格式yyyy-MM转换为具有休眠状态的日期

时间:2015-07-24 17:02:03

标签: java hibernate date spring-annotations

当我尝试在我的属性顶部使用@DateTimeFormat(patter="yyyy-MM")时,

  

错误:org.hibernate.engine.jdbc.spi.SqlExceptionHelper - 格式错误   日期'2015-05'

我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:0)

As I test, format lick "yyyy-MMM", "yyyy-MM-dd" all working. The "yyyy-MM" format is not supported by @DateTimeFormat. Then, for getting around, I need attributeConverter or wave magic in getter and setter

答案 1 :(得分:0)

也许您可以使用更合适的Java类型, 例如org.joda.time.YearMonth(Joda Time 2.0)或java.time.YearMonth(Java 8)。 例如,YearMonth.now()给出“2015-09”。

然后你需要一个从String到YearMonth的转换器。

使用Hibernate,您可以在您的实体上使用:

@org.hibernate.annotations.Type(type = "MyConverter")
private YearMonth yearMonth;

使用JPA 2.1:

@javax.persistence.Convert(converter = MyConverter.class)
private YearMonth yearMonth;