0

When I tried to use @DateTimeFormat(patter="yyyy-MM") at top of my attribute,

ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Bad format for DATE '2015-05'

What Can I do to solve this problem?

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
Neil
  • 2,714
  • 11
  • 29
  • 45
  • 1
    this is a SQL exception, it doesn't understand dates with such format, ie missing day. – Woland Jul 24 '15 at 17:13
  • The String date in Database is all with format as "yyyy-MM", like("2015-03"), How can I convert this string to Date hibernate pojo – Neil Jul 24 '15 at 17:23
  • Did you try "pattern" instead of "patter"? – Elliott Frisch Jul 24 '15 at 18:02
  • 1
    your date is saved as 2015-03 in sql database? What data type are you using for that? – Woland Jul 25 '15 at 01:02
  • @Walter are you sure column type in DB is date? which DBMS are you using? – Amogh Jul 25 '15 at 07:15
  • The data type in DB is varchar with format "yyyy-MM" – Neil Jul 26 '15 at 01:24
  • You cannot convert to date because date format is not correct. It is missing day in the date. As you mentioned the data type in db is varchar ( which is not date), why you want to convert to date ? Anyways, in short you can't do this. – Utkarsh Jul 26 '15 at 03:38

2 Answers2

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

Neil
  • 2,714
  • 11
  • 29
  • 45
0

Maybe you could use a more appropriate Java type, like org.joda.time.YearMonth (Joda Time 2.0) or java.time.YearMonth (Java 8). For example, YearMonth.now() gives "2015-09".

Then you would need a converter from String to YearMonth.

With Hibernate you can use on your entity :

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

With JPA 2.1 :

@javax.persistence.Convert(converter = MyConverter.class)
private YearMonth yearMonth;
Guillaume Husta
  • 4,049
  • 33
  • 40