Saturday 1 March 2008

character data type

Another little mapping issue between PostgreSQL and Hibernate. A varchar or character varying data type maps quite happily to a java String. However, a character data type does not. When attempting to do so you get something along the lines of:

javax.persistence.PersistenceException: org.hibernate.HibernateException: Wrong column type: char_column, expected: varchar(2)

To address this, you need to define the correct datatype for Hibernate to understand, and it is not "char" or "char(2)" or "character", as suggested in what references I could find, including Hibernate in Action. Instead the correct value is "bpchar". So if using annotations, it would look something like:

@Column(name = "char_column", length = 2, columnDefinition="bpchar")
@Length(min = 2, max = 2)
public String getCharColumn() {
return this.charColumn;
}

For a database schema definition that went something like:

char_column character(2) DEFAULT NULL::bpchar

Yet using direct jdbc, it works with no mapping issues at all, just like the uuid datatype does. Which raises the concern with JPA in general, and Hibernate in particular, how difficult is it to use these ORM frameworks and still have database agnostic, portable code? My code would not be coupled to the ORM mapping quirks per DB dialect if I just went completely with jdbc. Yet I was always under the impression that one of the benefits of these frameworks was that they were meant to hide much of the DB dialect differences from you and allow you to have more portable code. However, it would appear in reality to be just the reverse.

2 comments:

Anonymous said...

THANK YOU SO MUCH :-D

Cleydyr 'Zambo' Bezerra de Albuquerque said...

It still helps random people around the internet. XD Thank you so much!