I am trying to execute a query like the following, using HQL, that uses a native SQL function (dbms_lob.getlength
):
def results = Attachment.execute
In Attachment
domain add new field Long fileBytesLength
and inside mapping closure add the formula for calculating the length of fileBytes
field.
class Attachment {
String createUserName
String originalFilename
byte[] fileBytes
Long fileBytesLength
Date dateCreated
//Other Properties
static mapping = {
//Other mappings
fileLength formula: "dbms_lob.getlength(fileBytes)"
}
}
And then modify the query to:
def results = Attachment.executeQuery(
'select id, originalFilename, fileBytesLength, dateCreated, createUserName '+
'from Attachment a where a.id not in '+
'(select attachmentId from SpecVersion sv where sv.attachmentId is not null) '+
'and a.dateCreated > sysdate - 30')
You can always use basic java jdbc connection in order to execute query. Create the java code for this and store it in src/java/.
Well i achieved this by adding custom functions like this in an Overwritten dialect.
class MySqlDialect extends MySQL5InnoDBDialect {
public MySqlDialect() {
super();
registerFunction("date_add_interval", new SQLFunctionTemplate(StandardBasicTypes.DATE, "date_add(?1, INTERVAL ?2 ?3)"));
registerFunction("date_sub_interval", new SQLFunctionTemplate(StandardBasicTypes.DATE, "date_sub(?1, INTERVAL ?2 ?3)"));
registerFunction("to_date", new SQLFunctionTemplate(StandardBasicTypes.DATE, "str_to_date(?1, ?2)"));
registerFunction("minutes_diff", new SQLFunctionTemplate(StandardBasicTypes.LONG, "timestampdiff(MINUTE, ?1, ?2)"));
}
public String openBlobSelectQuote() {
return "`";
}
public String closeBlobSelectQuote() {
return "`";
}
}
Update : Function Registration:
registerFunction("getlength", new SQLFunctionTemplate(StandardBasicTypes.LONG, "dbms_lob.getlength(?1)"));
Your HQL Query:
def results = Attachment.executeQuery(
'select id, originalFilename, getlength(a.fileBytes), dateCreated, createUserName '+
'from Attachment a where a.id not in '+
'(select attachmentId from SpecVersion sv where sv.attachmentId is not null) '+
'and a.dateCreated > sysdate - 30')