2020-04-20

Spring: Implicit CLOB to String

So you have a stored procedure, which has an OUT parameter, with the type of CLOB.
You want to get the contents. It seems easy, right?

Well, you just need to actually ask Hibernate to turn it into a String for you in one easy step, using org.hibernate.type.MaterializedClobType:

PROCEDURE that_one_procedure(
    P_ARG1        IN  VARCHAR2,
    P_ARG2        IN  VARCHAR2,
    P_ARG3        IN  VARCHAR2,
    X_SOME_OUTPUT OUT NOCOPY CLOB
);

// Excerpt of an Entity class...
import org.hibernate.type.MaterializedClobType;

@NamedStoredProcedureQuery(name = "querySomeProcedure", procedureName = "MY_PACKAGE.THAT_ONE_PROCEDURE",
 parameters = {
   @StoredProcedureParameter(name = "P_ARG1", 
     type = String.class),
   @StoredProcedureParameter(name = "P_ARG2", 
     type = String.class),
   @StoredProcedureParameter(name = "P_ARG3", 
     type = String.class),
   @StoredProcedureParameter(name = "X_SOME_OUTPUT", 
     mode = ParameterMode.OUT, 
     type = MaterializedClobType.class) /* <-- !!! */

Now my Repository can look like this:
// Excerpt of a Repository...
@Procedure(name = "querySomeProcedure", outputParameterName = "X_SOME_OUTPUT")
 String querySomeProcedure(@Param("P_ARG1") String someArg,
   @Param("P_ARG2") String thatAnotherArg,
   @Param("P_ARG3") String alsoAnArg);

See, all the magic is done by Hibernate.