Reputation: 521
I am working in a spring project, where I use hibernate 3.5.5-Final and my database is MySQL. My code is bellow
String sql = "INSERT INTO recently_sold_products (product_id, sell_time) VALUES ('9749', '2016-06-01 00:00:00')";
Query query = getCurrentSession().createSQLQuery(sql);
System.out.println("Updating recently sold products. Row = " + query.executeUpdate());
This give me output Like
Updating recently sold products. Row = 1
But when i check the database table, I found no row.
In this table product_id is primary key. If I try to insert a duplicate product_id then I found the error messages, Duplicate entry '9749' for key 'PRIMARY', which confirm that the query reach in the database. But if I try to insert a normal row then the output of executeUpdate() method is 1, but no row insert in table.
I cannot understand what happen.
Upvotes: 1
Views: 737
Reputation: 9
Everything seems fine, but the problem is rollback. After executeUpdate;
add this:
connection.commit(); //Whatever you are using as con. string.
Upvotes: 1
Reputation: 427
From what little I know about Hibernate it would seem that you should be controlling your sessions and transactions more carefully.
Some library or database configurations allow you to run multiple queries in a session without committing the data and allowing future sessions to see the changes made. What is happening is you're changing data in the session but then ending the session and rolling the data back so no other sessions can see it (It didn't happen).
Open a session, start a transaction (or query), commit your session, close your session.
This is the order you'll want to do things. If you're not creating the session and storing it as a variable you COULD use getCurrentSession().getTransaction().commit() after your query and this SHOULD work but you're not controlling your sessions very well by doing this and could get weird errors if something behind the scenes doesn't happen in the right order.
Upvotes: 0