OJB / Oracle XE sql debug-display problem - java

I have a Java application, and use OJB as my ORM technology. I have an Oracle XE installation locally to develop against. The problem is when I need to debug a problem, I like looking at the SQL output. Here is an example of SQL I can view through the "Top SQL" interface in Oracle XE:
select a_bunch_of_fields
from KREW_DOC_TYP_T A0
WHERE ((UPPER(A0.DOC_TYP_NM) LIKE :1) AND A0.ACTV_IND = :2) AND A0.CUR_IND = :3
The problem is I would like to see the real value instead of ":1". I can't seem to find how I can configure this. I know the real values are working, because the application is responding as expected, for the most part (hence the bugs I am working on).
Thanks,
Jay

One quick and dirty way is to look in the provided database views (v$sql_bind_capture and v$sqlarea). In the SQL below, I just added a like clause to match the sql statement you have above, you will then get a row for each bind variable and it's value. To target a very specific SQL statement you want the sql_id for your query.
SELECT a.sql_text, b.NAME, b.POSITION, b.datatype_string, b.value_string
FROM v$sql_bind_capture b, v$sqlarea b
WHERE b.sql_id = a.sql_id
and a.sql_text like '%UPPER(A0.DOC_TYP_NM) LIKE :1%'
Output (without the SQL the result would look look something like this):
"NAME","POSITION","DATATYPE_STRING","VALUE_STRING"
":B1","2","NUMBER","1001"

Related

Criteria JPA - Call Postgres CAST function

I'm trying to call a Postgres function with Criteria but it's not working. I need to use the LIKE clause in a UUID field, so I need to convert into VARCHAR first.
The result I need:
SELECT * FROM my_table WHERE cast(uuid as varchar(36)) like '%1234%';
What I'm doing in Criteria:
final Path<UUID> uuidField = from.get("uuid");
var cast = cb.function("cast", String.class, uuidField, cb.literal("as varchar(36)"));
cb.like(cast, String.format("%%%s%%", stringValue));
The query which is being generated:
HQL: select generatedAlias0 from com.MyTable as generatedAlias0 where function('cast', generatedAlias0.uuid, 'as varchar(36)') like '%1234%' order by generatedAlias0.name asc
Error:
2022-08-08 18:38:48,549 WARN [io.ver.cor.imp.BlockedThreadChecker] (vertx-blocked-thread-checker) Thread Thread[vert.x-eventloop-thread-9,5,main] has been blocked for 2393 ms, time limit is 2000 ms: io.vertx.core.VertxException: Thread blocked
at antlr.ASTFactory.make(ASTFactory.java:342)
at antlr.ASTFactory.make(ASTFactory.java:352)
at org.hibernate.hql.internal.antlr.HqlBaseParser.jpaFunctionSyntax(HqlBaseParser.java:4633)
at org.hibernate.hql.internal.antlr.HqlBaseParser.primaryExpression(HqlBaseParser.java:1075)
The log is not so clear (I'm using Quarkus + Hibernate Reactive), but I suspect it crashed in database because the function('cast', generatedAlias0.uuid, 'as varchar(36)').
I think it should be something like: function('cast', generatedAlias0.uuid, as varchar(36)) (without quotes). But I don't know how to achieve this result to test my theory.
How can I call this CAST function?
After investigating some possible solutions (I'm avoiding to create custom database routines) I found something interesting in a answer from another question:
Currently JPA does not have APIs for replace() and cast(string as numeric). But you can use CriteriaBuilder.function(...) to create database native functions if database portability is not critical.
Source: JPA criteria builder: how to replace and cast a string to numeric in order-by?
I don't know if this is documented is some place, but assuming that there is no way to call CAST(x AS y) using Criteria, I tried a workaround to force the UUID to VARCHAR cast without using the probably unsupported CAST function.
I tested this direct SQL query to database:
SELECT * FROM my_table WHERE concat(uuid, '') like '%123%';
And it works. This CONCAT forces the cast to VARCHAR and the LIKE function does his job. Knowing this, I did:
final Path<UUID> uuidField = from.get("uuid");
var cast = cb.function("concat", String.class, uuidField, cb.literal(""));
cb.like(cast, String.format("%%%s%%", stringValue));
Worked perfectly. I hope this help someone else.
As #HaroldH said, it's a weird requirement, but happened in my project.

How to add multiline Strings in Java?

How to make long queries more readable?
For example I have this one:
String query = "SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE username = 'username' AND user_password = crypt('password', user_password)) THEN 'match' ELSE 'differ' END";
And it's completely unreadable, are there any ways to beautify it?
Since Java 15, you can use text blocks:
String query = """
SELECT CASE
WHEN
EXISTS (
SELECT *
FROM users
WHERE
username = 'username'
AND user_password = crypt('password', user_password)
)
THEN 'match'
ELSE 'differ'
END
""";
In cases when you don't wont to blend SQL and JAVA you can put SQL queries in an .sql file. And get this text when needed.
public class QueryUtil {
static public String getQuery(String fileName) throws IOException {
Path path = Paths.get("src/test/resources//" + fileName + ".sql");
return Files.readAllLines(path).get(0);
}
}
If you can mix SQL and JAVA then starting from JDK15 you can use text blocks for this.
Also you can generates Java code from your database by using JOOQ, it gives many benefits.
Assuming that you can't move to a newer-than-8 version of Java (or even if you can), by far the best solution is to use an ORM. For Java it pretty much comes down to Hibernate, or jOOQ. jOOQ (and possibly Hibernate, I haven't used it so can't say, sorry) allows you to use a fluent programming interface, which is very much in keeping with existing Java code style and patterns.
Another specific advantage of using an ORM is that you can very easily change which DB engine you use without having to change the Java code that you've written beyond changing the SQL dialect in your setup functions. See https://www.jooq.org/javadoc/latest/org.jooq/org/jooq/SQLDialect.html.
You can use JOOQ and get multiple other benefits like type safety, auto-complete, easy mapping and great support.
Have used it for several projects so far and also competition like Kotlin Exposed but always came back to JOOQ.
Move to Java 13+. There are Text Blocks for this.
Or use some ORM library.

Using SQLExpression from QueryDsl

I want to use the SQLExpressions from QueryDsl. I have a Q-object called qMyClass. Now I want to use the listagg function of the oracle database. Therefore i want to initialize a WithinGroup-object.
WithinGroup<Object>.OrderBy withinGroup = SQLExpressions.listagg(qMyClass.attributeName, "/").withinGroup().orderBy(qMyClass.attributeName);
The first part
SQLExpressions.listagg(qMyClass.attributeName, "/")
already gives me the error:
unknown operation with operator LISTAGG and args
[myClass.attributeName, /]
Does anyone know how to use listagg? Didn't find any helpful information on the web. I am using version 4.0.2 of QueryDsl. Thanks!
Try something like this:
select(
qMyClass.id,
SQLExpressions.listagg(qMyClass.attributeName,"/")
.withinGroup()
.orderBy(qMyClass.attributeName.asc())
.getValue()
.as("foo"))
.from(qMyClass)
.groupBy(qMyClass.id);

Save the result set of a query against a view to a table using the java client library

Recently, one of our clients reported not being able to create a table based on a query against a view. That said, they were able to save the result of a query against a table into another table. This issue spawned a more implementation focused question using the Java client libraries. Specifically, is there any way to save the result set of a query against a view to a table using the Java client library? I will be digging and post anything that I find. That said, any early guidance would be appreciated!
To be specific and add more context, I note that the the following process failed when the query was run against a union view.
java -jar BigQueryToCloudExporter.jar ./GAFastAccessKey.p12 '' "
Select date(date_add('2014-08-09',floor(datediff(date(sec_to_timestamp(visitstarttime)),'2014-08-03')/7)*7,"DAY")) WeekEndDate
, hits.eventinfo.eventaction GA_RentalNo
, count(distinct visitID) PDP_PPC
FROM (TABLE_DATE_RANGE([Union_View.GA],
TIMESTAMP('2014-08-30'),
TIMESTAMP('2014-09-13')))
where hits.eventinfo.eventcategory='property attributes'
and brandId=121
--hits.eventinfo.eventcategory='property inquiry'
and trafficsource.medium like '%cpc%'
--and trafficsource.campaign not like '%ppb%'
and trafficsource.campaign like '%mpm%'
group each by WeekEndDate, GA_XXXXXX
order by WeekEndDate, GA_XXXXXX limit 100" StagingQueryTable QueryTable AVRO gs://XXXXXX/QueryTable*.avro
On the other hand, the following process succeeded when the query was made against a BigQuery table (keeping everything else same).
java -jar BigQueryToCloudExporter.jar ./GAFastAccessKey.p12 '' "
Select date(date_add('2014-08-09',floor(datediff(date(sec_to_timestamp(visitstarttime)),'2014-08-03')/7)*7,"DAY")) WeekEndDate
, hits.eventinfo.eventaction GA_XXXXXX
, count(distinct visitID) PDP_PPC
FROM (TABLE_DATE_RANGE([XXXXXX.ga_sessions_],
TIMESTAMP('2014-08-30'),
TIMESTAMP('2014-09-13')))
where hits.eventinfo.eventcategory='property attributes'
and brandId=121
--hits.eventinfo.eventcategory='property inquiry'
and trafficsource.medium like '%cpc%'
--and trafficsource.campaign not like '%ppb%'
and trafficsource.campaign like '%mpm%'
group each by WeekEndDate, GA_RentalNo
order by WeekEndDate, GA_XXXXXX limit 100" StagingQueryTable QueryTable AVRO gs://XXXXXX/QueryTable*.avro

IntelliJ IDEA code inspection: HQL custom dialect & registered functions

My question is about
using registered functions for date/time manipulations in Hibernate Query Language and
IntelliJ IDEA's code inspection for these registered functions in HQL.
I'm using Hibernate 4.2.5 with Java 7, and SQL Server 2008 R2 as the database, and IntelliJ IDEA 12.1.6.
In an HQL query I need to perform the TSQL DATEADD function - or the equivalent HQL date operation. This doesn't seem to exist.
Here's what I'd like to achieve:
update MyTable set startTime = GETDATE(), targetTime = DATEADD(HOUR, allocatedTime, GETDATE()), endTime = null where faultReport.faultReportId = :faultReportId and slaTypeId = :slaTypeId
Searching for answers online has been disappointingly no help, and the most common advice (like the comment seen here: https://stackoverflow.com/a/18150333/2753571) seems to be "don't use date manipulation in hql." I don't see how I can get around performing the operation in the SQL statement in the general case (e.g. when you want to update one column based on the value in another column in multiple rows).
In a similar fashion to the advice in this post: Date operations in HQL, I've subclassed a SQLServerDialect implementation and registered new functions:
registerFunction("get_date", new NoArgSQLFunction("GETDATE", StandardBasicTypes.TIMESTAMP)); // this function is a duplication of "current_timestamp" but is here for testing / illustration
registerFunction("add_hours", new VarArgsSQLFunction(TimestampType.INSTANCE, "DATEADD(HOUR,", ",", ")"));
and added this property to my persistence.xml:
<property name="hibernate.dialect" value="my.project.dialect.SqlServerDialectExtended" />
and then I'm testing with a simple (meaningless, admitted) query like this:
select x, get_date(), add_hours(1, get_date()) from MyTable x
The functions appear to be successfully registered, and that query seems to be working because the following SQL is generated and the results are correct:
select
faultrepor0_.FaultReportSLATrackingId as col_0_0_,
GETDATE() as col_1_0_,
DATEADD(HOUR,
1,
GETDATE()) as col_2_0_,
... etc.
But I now have this problem with IntelliJ IDEA: where get_date() is used in the HQL, the code inspection complains "<expression> expected, got ')'". This is marked as an error and the file is marked in red as a compilation failure.
Can someone can explain how to deal with this, please, or explain what a better approach is? Am I using the incorrect SQLFunction template (VarArgsSQLFunction)? If yes, which is the best one to use?
I'd like the usage of the registered function to not be marked as invalid in my IDE. Ideally, if someone can suggest a better way altogether than creating a new dialect subclass, that would be awesome.

Categories

Resources