I'm trying to setup hibernate in a project, and as part of it, I'm trying to do a simple update query just to make sure that its able to work. Here's my code:
Session sess = factory.openSession();
sess.beginTransaction();
sess.createSQLQuery("UPDATE fooTable SET bar='baz' ");
sess.getTransaction().commit();
sess.close();
When I run the code, everything executes without any error messages, and I see debug messages about getting a JDBC driver (using the config info I've provided), but the update query doesn't seem to be executed, as the table still shows the old info.
What am I doing wrong?
You created the query, but didn't execute it.
...
Query qry = sess.createSQLQuery("UPDATE fooTable SET bar='baz' ");
int updatedRows = qry.executeUpdate();
...
Related
I'm using MySQL DataBase to learn Hibernate from video tutorial
i'm doing Step by step, and when i'm trying to execute query to update in dataBase on all records "Error interpreting query occurs". the wierd part is that the person who is executing the same query passess withouth any problem
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
Query email = session.createQuery("UPDATE Student SET email=:email");
email.setParameter("email", "code#gmail.com");
email.executeUpdate();
session.getTransaction().commit;
session.close();
}
I expect that all emails from dataBase will be updated but instead of executing query i get
Exception in thread "main" org.hibernate.query.sqm.InterpretationException: Error interpreting query [update Student set email=:email];this may indicate a semantic (user query) problem or a bug in the parser at org.hibernate.query.sqm.produce.internal.SemanticQueryProducerImpl.interpret(SemanticQueryProducerImpl.java:66)
OK i found out what is the problem, i used hibernate-core 6Alpha release. I switched to 5.4.2.Final and everything is executing without any problems
We have a function in our application that cleans up the database and resets the data, we call a method cleanup() which at first deletes all the data from the database and then calls a sql script file to insert all the necessary default data of our application. Our application supports Oracle - MySQL and MSSQL, the function works fine on both Oracle and MySQL but doesn't work as it supposed to on MSSQL.
The problem is that it is clearing all the data from the database but not inserting the default data, the first section of the method works fine but the second section doesn't get committed to the database. Here is the function:
public boolean cleanup(...){
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// delete and drop sql queries here...
tx.commit();
session.close();
// end of first section
session = sessionFactory.openSession();
tx = session.beginTransaction();
// insert default data sql queries here...
tx.commit();
session.close();
// end of second section
}
The database gets cleared successfully, but the default data is not being inserted to the database. Please let me know what am I doing wrong here. I tried doing both delete and insert sections in one transaction with no luck.
I want to run an Update query using createNativeQuery in entityManager. I am not able to run it.
My class structure :
class ABC_DAO
{
List<a> = entityManager.createNativeQuery(select.......); //sql1 : it is working fine
Sysout("some value"); // it is working
entityManager.createNativeQuery(update.......);// ***sql2 :it is not working***
Sysout("some value"); // it is working
}
Hibernate is not executing sql2 but executing sql2. We are using Postgres db. This query has to be in Sql. We are using Hibernate with JPA.
Let my try to help you on behalf of your erroneous code example and problem description.
1) You will only get a List as result of a query if you call getResultList() on it, otherwise sql1 would not work (Please post the complete code, if you want to get help):
List<a> = entityManager.createNativeQuery("sql1", a.class).getResultList();
2) For update statements you have to call the method executeUpdate() and not getResultList() (or getSingleResult())to send the native SQL statement to the database:
int countUpdated = entityManager.createNativeQuery("sql2").executeUpdate();
I am trying to create events using Java code with hibernate. I verified my syntax for CREATE EVENT in MySQL Workbench, and I verified my Java code with a simple UPDATE query. But when I am trying to use both it just doesn't work. I am not getting any error message, just that 0 rows were affected. My code is as follows:
String sql = "CREATE EVENT IF NOT EXISTS test_event ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 20 SECOND ON COMPLETION PRESERVE ENABLE DO UPDATE my_table SET last_error_message='my test' WHERE ID=17;";
session.beginTransaction();
SQLQuery query = session.createSQLQuery(sql);
int result = query.executeUpdate();
session.getTransaction().commit();
....
session.close();
thanks a lot
How do you know if any new events were created? You can try
show events from <SCHEME_NAME>;
This will show all the events that are registered to the given schema.try printing the session\statement warning stack...
Get jdbc connection from your session: How to get jdbc connection from hibernate session?
Use JDBC to execute DDL
...
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
// ...
} finally {
// close stmt
}
...
First, you need to make sure your database is prepared to execute an event. for that, you need to run the following command.
SHOW PROCESSLIST;
MySQL uses a special thread called event schedule thread to execute all scheduled events.
if you see your process list like the above picture. you need to run the below command to enable MySQL event execution.
SET GLOBAL event_scheduler = ON;
Then when you execute the "SHOW PROCESSLIST;" command you will see the below list which shows the specific thread for event execution in MySQL.
Now you can create your event using any MySQL client interface.
I have code which updates a column in a database which looks like this:
logger.info("Entering Update Method");
Query query =session.createQuery("update CardMaster cm set cm.otpAmount = :otpAmount" + " where cm.cardNumber = :cardnumber");
double otpAmount= cardMaster.getOtpAmount();
String cardNumber=cardMaster.getCardNumber();
query.setParameter("otpAmount",otpAmount);
query.setParameter("cardnumber",cardNumber);
query.executeUpdate();
logger.info("cardMasterUpdated successfully");
In this I am getting otpamount ,cardnumber and it is giving result of executeupdate as 1 but it is not reflecting in Database .. I am opening the session and committing correctly outside.
Instead of using this, if I use update() of hibernate it is happening correctly.
Can you help me out of this?
You have to commit the transaction.
Since you do not commit, nothing is visible for other processes, like the tool you are using to view your DB.
You can acquire your transaction with session.getTransaction(). However, normally you start your transaction manually like this:
Transaction tx = session.beginTransaction();
// Do your stuff
session.flush();
tx.commit()