Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

Convert HQL query into SQL in Java logs

I have a sample query like the following

String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setParameter("stockCode", "7277")
.list();

the result is a list like I expect it to be but I want to know how I can sysout the sql query in my Tomcat logs before the query is executed. Can I do it at the code level as opposed to setting a property in log4j or hibernate config?

In this case, I am looking for an output like

select * from Stock s where s.code = 123;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To access SQL at the code level, you can use the datasource proxy library with a listener.

You can find the example of the datasource proxy and its listener at my github repo jpa-puzzles.

However, if you only want to see the sql-s with bound parameters (show-sql shows only sql-s without bound parameters), it's easier to use a hibernate configuration:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...