How can I check what parameter is finally passed with the query? - java

Is there any way I can check, how is the query being framed or what values are being passed ? I want to check for this query :
String hql = "from Scheduled where stime <= current_time()"; // QUERY
List list = session.createQuery(hql).list();
I want to know what value of current_time() is being sent ?

current_time() is not replaced with a specific time in hibernate - it is passed as part of the SQL to the database and is evaluated there. Therefore, current_time() will be whatever the current time is on the database server at the time the statement is executed.

You can enable Hibernate logging and these two params should be of help to you:
org.hibernate.SQL - Log all SQL DML statements as they are
executed
org.hibernate.type - Log all JDBC parameters

If your underlying database is SQL Server, then another option is SQL Profiler.

Here are entries from log4j.properties which works for me to print hibernate queries and parameters.
log4j.logger.org.hibernate=DEBUG, stdout
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE,stdout

Related

Update and Return Updated column using returning keyword in same query in java jdbc code

update account set lastusedval=lastusedval+1 where isactive=1 returning
lastusedval;
How to execute above query in java?
when i tried to execute in oracle its working but in java hibernate/jpa no way to store return value in update query.
By executing above query intention is to apply lock on db level when more than 1 request comes
Using jdbc prepared statement with registeroutparameter might help you to resolve this issue.
Creating an UPDATE RETURNING query in Hibernate

Inspect limit parameter values for SQLServer2008Dialect

I have an hibernate query with paging. I want to see parameter values related to the paging. I use SQLServer2008Dialect so my query looks like:
WITH query AS (/* criteria query */ select
ROW_NUMBER() OVER (
order by
this_.event_id desc)
...
...
) SELECT
*
FROM
query
WHERE
__hibernate_row_nr__ BETWEEN ? AND ?
I set
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.use_sql_comments = true
in hibernate config used by my application.
I enabled also logging query parameters in log4j by setting
org.hibernate.type.descriptor.sql.BasicBinder to TRACE level.
This works fine for fine for all other parameters but I can't see parameter values related to the row number limit. Is there any way to inspect which are the current limit parameter values?
In the past I've always used that configuration with hibernate, but recently I've switched to use BoneCP which allows to me log the exact query being executed to avoid having the same problem you are facing.
If you can use BoneCP, you could configure your data source to enable logging statements, and set a log4j logger for com.jolbox.bonecp to debug, and you are set.

Get dynamic SQL column names from Hibernate

I have an Oracle table that has a CLOB in it. Inside this CLOB can be a SQL statement. This can be changed at any time.
I am currently trying to dynamically run these SQL statements and return the column names and data back. This is to be used to dynamically create a table on the web page.
Using Hibernate, I create the query and get the data like so:
List<Object[]> queryResults = null;
SQLQuery q = session.createSQLQuery(sqlText);
queryResults = q.list();
This gets the data I need, but not the column names. I have tried using the getReturnAliases() method, but it throws an error that the "java.lang.UnsupportedOperationException: SQL queries do not currently support returning aliases"
So my question is: Is there a way through Hibernate to get these values dynamically?
You can use :
q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map<String,Object>> aliasToValueMapList=query.list();
to get column names in createSQLQuery.
For more details please refer to this question.
You can use the addScalar method to define the columns.
Look at 16.1.1
https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querysql.html
You could implement a ResultTransformer ( http://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/transform/ResultTransformer.html ) and set it on the native query. I think with a native SQL query you get the aliases as specified in the SQL as alias parameter in the callback method.
In 2018 I would suggest using NativeQueryTupleTransformer with native queries.
query.setResultTransformer(new NativeQueryTupleTransformer());
The result format is List<Tuple>. This format is very convenient to work with native SQL queries.

Hibernate multiple native SQL statements

I want to run a native SQL from a file using Hibernate. The SQL can contain several statements creating the database structure (i.e. tables, constraints but no insert/update/delete statements).
Example, very simple query is below (which contains the following two SQL statements)
CREATE DATABASE test;
CREATE TABLE test.testtbl( id int(5));
I am using MySQL db, and when I run the above query I am gettng syntax error returned. When I run them one by one, its ok.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'CREATE TABLE test.testtbl( id int(5))' at line 1
The code to run the query is below (above statement is assigned to 'sql' variable):
session = sf.openSession();
session.beginTransaction();
Query qry = session.createSQLQuery(sql);
qry.executeUpdate();
session.getTransaction().commit();
Any help would be appreciated.
As others have explained
You must run these queries one by one.
The hibernate code gets translated into running one update statement on JDBC.
But you provided two update statements.
In addition,
I personally prefer to have the code that creates tables outside of the Java application, in some DB scripts.
The parameters of the method createSQLQuery is t-sql code;
t-sql code to ensure that in the mysql interface analyzer correctly.
You can try changed the sql :'CREATE TABLE testtbl(id int(5));'
by the way you can use JDBC Connection api (Don't recommend to do so)
Such as:
java.sql.Connection conn=session.connection();

Toplink bug. Empty result for valid sql with not empty result

How is it possible?
We are executing EJBQL on Toplink(DB is Oracle) and query.getResultList is empty.
But!
When i switched log level to FINE and received Sql query, that TopLink generates, i tried to execute this query on database and (miracle!) i got a non-empty result!
What could be the reason and how is it treated?
Thanks in advance!
P.S. No exceptions.
UPDATE:
Query log:
SELECT DISTINCT t0.ID, t0.REG_NUM, t0.REG_DATE, t0.OBJ_NAME, t1.CAD_NUM, t1.CAD_NUM_EGRO, t2.ID, t2.DICT_TYPE, t2.ARCHIVE_DATE, t2.IS_DEFAULT, t2.IS_ACTUAL, t2.NAME, t0.INVENTORY_NUM FROM CODE_NAME_TREE_DICTIONARY t3, DEFAULTABLE_DICTIONARY t2, IMMOVABLE_PROP t1, ABSTRACT_PROPERTY t0 WHERE ((t3.ID IN (SELECT DISTINCT t4.ID FROM CODE_NAME_TREE_DICTIONARY t5, CODE_NAME_TREE_DICTIONARY t4, type_property_parents t6 WHERE (((t5.ID = ?) AND (t4.DICT_TYPE = ?)) AND ((t6.type_property_id = t4.ID) AND (t5.ID = t6.parent_id)))) AND ((t1.ID = t0.ID) AND (t0.PROP_TYPE_DISCR = ?))) AND ((t3.ID = t0.PROP_TYPE) AND ((t2.ID (+) = t1.STATUS_ID) AND (t2.DICT_TYPE = ?)))) ORDER BY t0.REG_NUM ASC
bind => [4537, R, R, realty_status]|#]
This query returns 100k rows, but toplink believes that it is not...
With log level to FINE can you verify that you are connecting to the same database? How simple is your testcase; can you verify that it is this exact JPQL that is being translated to that SQL?
VPD (http://download.oracle.com/docs/cd/B28359_01/network.111/b28531/vpd.htm)? Policies?
Is something of this flavor defined on the schema? These features transparently add dynamic where clauses to the statement that is executed in the database session, so the query results depend on the state of the session in this case.
When reformatting the query the following conditions seemed strange:
AND t2.ID (+) = t1.STATUS_ID
AND t2.DICT_TYPE = ?
The (+) indicates an outer join of t2 (DEFAULTABLE_DICTIONARY), but this table seems to be non-optional since it has to have a non-null DICT_TYPE for the second condition.
On closer looking, the bind parameters also seem to be off, the fields are in order
CODE_NAME_TREE_DICTIONARY.ID
CODE_NAME_TREE_DICTIONARY.DICT_TYPE
ABSTRACT_PROPERTY.PROP_TYPE_DISCR
DEFAULTABLE_DICTIONARY.DICT_TYPE
With the given parameters (4537, R, R, realty_status), the first DICT_TYPE would be 'R' while the second is the string "realty_status" which seems inconsistent.
Transactions? Oracle never gives you a "dirty read" which database speak for access to uncommitted data. If you send data on one connection you cannot access it on any other connection until it is committed. If you try the query later by hand, the data has been committed and you get the expected result.
This situation can arise if you are updating the data in more than one connection, and the data manipulation is not set to "auto commit". JPA defaults to auto-commit, but flushing at transaction boundaries can give you a cleaner design.
I can't tell exactly, but I am a little surprised that the string parameters are not quoted. Is it possible that interactively there are some automatic conversions, but over this connection instead of the string 'R' it was converted to the INT ascii for R?
I found the reason!
The reason is Oracle! I've tried the same code on Postgres and its worked!
I dont know why, but in some magic cases oracle ignores query parameters and query returns empty result.

Categories