Using Oracle XMLType column in hibernate

Viewed 25982

I need to map Oracle XMLType column to hibernate entity class. There is a working (and I think well-known) solution that involves implementing UserType; however, I cannot use it because requires importing Oracle xml parsers, which in turn causes many problems .
I'm ok with accessing value of xml column as a string and leave transformation to the code that manipulates entity, but I cannot find the way to read value from and write it to database. What I have tried so far:

  1. Declaring property in entity class as String . Result - value is read as null. If property is just Serializable, I get "cannot deserialize" exception.
  2. Using @Formula annotation (CAST xmlCol as varchar2(1000)). Result - value is not stored
  3. Using @Loader and putting CAST in SELECT. That was the most promising attempt - value was read and stored successfully, but when it comes to loading collection of entities that contain xml column, I get null (Hibernate doesn't use sql in @Loader if underlying table is LEFT JOINed).

Another approach that I believe should work is to have xml column as String (for writing) plus dummy field for reading with @Formula; however, it looks like a dirty hack to me, and I'd prefer not to do so unless I have no choice.

Finally, the very last thing I can do is to change DB Schema (also more that 1 option, like view + triggers, column data type change), but this is not a good option for me either.

I wonder if I missed something or maybe there is a way to make (3) work?

5 Answers

There exists an even more simple solution for this. Just use the ColumnTransformer Annotation.

@ColumnTransformer(read = "to_clob(data)", write = "?")
@Column( name = "data", nullable = false, columnDefinition = "XMLType" )
private String data;`

I had the issue when migrating from Hibernate 3.6.* to Hibernate 5.4, I resolved by adding dbUnit maven dependency before Oracle xmlparserv2. dbUnit has xerces:xercesImpl as transient dependency. This way I don't have to mess with App Server Config and unit tests runs just fine.

Related