Reputation: 5142
Is there a way to generate an Insert SQL query out of a bean instance? maybe using Hibernate code?
for example:
@Table(name = "tbl_a")
class A{
@Column(name = "col_a")
int a;
@Column(name = "col_b")
int b;
}
to INSERT INTO tbl_a (col_a,col_b) VALUES (avalue,bvalue)
So if I will provide it with an A instacne which has a = "val" and b = 5 I will get:
INSERT INTO tbl_a (col_a,col_b) VALUES ('val',5) ??
EDIT
It seems I am not understood well so let me explain: I know how to persist with Hibernate. What I want is the actual class that generated the SQL query itself. The same query that will eventually be committed to the DB. But I need the Query string. Meaning, that I need a tool (or use Hibernate's class) which gets an object and returns a simple string containing the SQL query. (not in a log).
I hope it's is better now.
Thanks, Idob
Upvotes: 2
Views: 2184
Reputation: 2770
OK, so there is no tool which gets an object and returns a simple string containing the SQL query.But you can use getQueryString()
method of Query class. you will get whole HQL string except the runtime parameters.
If you are interested in SQL string then you can enable DEBUG on the log4j system of Hibernate and use JDBCAppender or some custom Appender to capture the native SQL.
Anyway this option will make your app very slow (hibernate generates a lot of debug).
Upvotes: 1
Reputation: 9182
Yes, you can call sessionFactory.getCurrentSession().save(new A())
to directly insert your instance. The executed SQL will look similar to how you described it. You can test this by turning on hibernate debugging by doing hibernate.show_sql=true
Upvotes: 0