Sunday, August 3, 2008

Using JPA with PostgreSql or MySql?

I found a pretty strange behaviour when I was trying to use JPA with Hibernate to connect to PostgreSql. Here is the scenario:

I create a JPA NamedQuery as follow:

SELECT J FROM Job J WHERE
( :id IS NULL OR J.id = :id )
It is fairly simple query. It takes "id" parameter if it passed in a non NULL value. The good thing on this query is you just need to create a single query and it can serve on 2 purposes. If a parameter "id" is provided, the result will be retricted to a single Job object, if it got a NULL value, the query will return a list of Job objects. Isn't it great?

So when I put this query to use on MySql enviornment, it works as I described. However, when I put this query to use on PostgreSql, it returns "org.hibernate.exception.SQLGrammarException: could not execute query". The PostgreSql log shows "could not determine data type of parameter". If the IS NULL checking is taken out, it runs perfectly. So I suspect there are problems in either JDBC driver or Postgresql, although I tends to believe it is a JDBC driver problem. After a day of research (googling and forum), there is still no exact answer. But there are some hints that when a NULL value is passing to PostgreSql, as Hibernate will serialize the Null to bytea type, which is not the same type as PostgreSql, so it cannot recognize the data type and cause the issue.

So a workaround solution suggested to use Hibernate query instead of JPA query. So when you use Hibernate query, you can specify the data type (e.g. org.hibernate.Hibernate.STRING) and let Hibernate to know what data type it is when a NULL is passed in.

Personally I love PostgreSql, however, so far, I face lots of trouble when I use PostgreSql as the database. This problem I mentioned above is only one of them. When I change to use MySql, it always work perfectly. Does it imply that there is something that is not mature when use PostgreSql? Further research is required.

No comments:

Post a Comment