Truncate/Delete From on Hibernate - java

Im having a problem when using DELETE FROM myEntity
I saw on my database that all the entry are gone, but when i tried to insert a previous existed entry, its still have the record from before i delete it.
Here's the code :
static SessionFactory session = NewHibernateUtil.getSessionFactory();
public Session membukaSession(){
return session.openSession();
}
public void clearRencanaPesan(){
Session sess = this.membukaSession();
Query query = sess.createQuery("delete from Rencanapesan");
query.executeUpdate();
}
So i tried using Truncate
And this is the code :
public void clearRencanaPesan(){
Session sess = this.membukaSession();
Query query = sess.createQuery("TRUNCATE Table Rencanapesan");
query.executeUpdate();
}
This one isn't working at all ##, the entry isnt deleted.
this is the error
Jun 18, 2012 11:01:54 PM org.hibernate.hql.ast.ErrorCounter reportError
SEVERE: line 1:1: unexpected token: TRUNCATE
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: node to traverse cannot be null!
Please help me, how can i truncate or delete all entry.
Thank you so much.

The query you've provided contains no error. My first guess was that the session gets out of sync after manually deleting it using the query. Session.flush() makes sure the session is synchronized with the underlying database.
public void clearRencanaPesan(){
Session sess = this.membukaSession();
Query query = sess.createQuery("delete from Rencanapesan");
query.executeUpdate();
}
// after you've made your changes and before closing the session.
sess.flush();

Related

Hibernate query bulk manipulation exception

With Hibernate, I am trying to execute a query by setting multiple values from list and executing it at the same time. Here is the code
public void savePriority(List<Integer> priorities,int typeid) {
String sql="update table conf_sr_type_baserule_assoc set n_priority=:priority where n_typeid=:typeid";
/*System.out.println("sql query in savePriority"+sql);*/
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
SQLQuery squery=session.createSQLQuery(sql);
tx.begin();
for(int priority:priorities){
squery.setParameter("priority", priority);
squery.setParameter("typeid", typeid);
squery.executeUpdate();
}
tx.commit();
session.close();
}
but I am getting an error:
org.hibernate.exception.SQLGrammarException: could not execute native bulk manipulation query
The problem comes from your SQL query, which is invalid.
It should be:
update conf_sr_type_baserule_assoc set n_priority=:priority where n_typeid=:typeid
instead of
update table conf_sr_type_baserule_assoc set n_priority=:priority where n_typeid=:typeid

hibernate query result not updating after change

I am having an issue with hibernate. the query result is not updating.
i have a simple query which checks customertable to see if the 'enabled' column = true. the query works fine. but when i change the colum value from 'true' to 'false' and run the same query... it still gives me 'true' as a result.
if i close the application and recompile, and run query again, it THEN shows false, but then again if i change it back to true.. it still shows 'false' result. what am I doing wrong?
public void isEnabled(String customer){
Session session = sessionFactory.openSession();
Transaction tx = null;
try{
tx=session.beginTransaction();
Query query = session.createQuery("FROM Customer WHERE enabled=true");
List qr = query.list();
boolean check = qr.iterator().hasNext();
boolean enabled;
sw = new ServerWriter(writer);
if(check){
for(Iterator itr = qr.iterator();itr.hasNext();)
{
Customer c =(Customer)itr.next();
enabled=c.geEnabled();
sw.sendMessage("Customer is enabled");
}
}else{
sw.sendMessage("Customer is not enabled");
}
} catch(HibernateException e){
if(tx!=null){tx.rollback();}
e.printStackTrace();
}finally{session.close();}
}
First you forgot to close the transaction:
session.getTransaction().commit();
The reason you get the same value when querying second time is Hibernate cache. You always have a first level cache and if you configured it, you can have a second level cache, too.
You can refresh the first level cache before executing the query with:
session.refresh()
If you happen to have a second level cache you can skip it with this hint:
query.setHint("org.hibernate.cacheMode", CacheMode.IGNORE);

Hibernate batch update: need to know the failed statement

I have a code looking like this:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
try {
for ( Customer customer: customers ) {
i++;
session.update(customer);
if ( i % 200 == 0 ) { //200, same as the JDBC batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
} catch (Exc e) {
//TODO want to know customer id here!
}
tx.commit();
session.close();
Say, at some point session.flush() raises an DataException, because one of the fields did not map into the database column size, one of those batch of 200 customers. Nothing wrong with it, data can be corrupted, it's ok in this case. BUT, I really need to know the customer id which failed. Database returns meaningless error message, not stating what was the params of the statement, etc. Catched exception also does not contain which customer did fail, only the sql statement text, looking like 'update Customer set name=?'
Can I somehow determine it using the hibernate session? Does it store somewhere the information about last entity it tried to save down?

Delay during commit (using JPA/JTA)

I would like to ask you for help with following problem. I have method:
String sql = "INSERT INTO table ...."
Query query = em.createNativeQuery(sql);
query.executeUpdate();
sql = "SELECT max(id) FROM ......";
query = em.createNativeQuery(sql);
Integer importId = ((BigDecimal) query.getSingleResult()).intValue();
for (EndurDealItem item : deal.getItems()) {
String sql2 = "INSERT INTO another_table";
em.createNativeQuery(sql2).executeUpdate();
}
And after executing it, data are not commited (it takes like 10 or 15 minutes until data are commited). Is there any way how to commit data explicitly or trigger commit? And what causes the transaction to remain uncommited for such a long time?
The reason we use nativeQueries is, that we are exporting data on some shared interface and we are not using the data anymore.
I would like to mention, that the transaction is Container-Managed (by Geronimo). EntityManager is created via linking:
#PersistenceContext(unitName = "XXXX", type = PersistenceContextType.TRANSACTION)
private EntityManager em;
Use explicitly the transaction commit:
EntityManager em = /* get an entity manager */;
em.getTransaction().begin();
// make some changes
em.getTransaction().commit();
This should work. The time of execution of all operation between .begin() and .end() depends of course also from the cycle you're performing, the number of row you're inserting, from the position of the database (the speed of the network matters) and so on...

Hibernate is not deleting my objects. Why?

I have just set up a test that checks that I am able to insert entries into my database using Hibernate. The thing that drives me crazy is that Hibernate does not actually delete the entries, although it reports that they are gone!
The test below runs successfully, but when I check my DB afterwards the entries that were inserted are still there! I even try to check it using assert (yes I have -ea as vm parameter). Does anyone have a clue why the entries are not deleted?
public class HibernateExportStatisticDaoIntegrationTest {
HibernateExportStatisticDao dao;
Transaction transaction;
#Before
public void setUp(){
assert numberOfStatisticRowsInDB() == 0;
dao = new HibernateExportStatisticDao(HibernateUtil.getSessionFactory());
}
#After
public void deleteAllEntries(){
assert numberOfStatisticRowsInDB() != 0;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
for(PersistableStatisticItem item:allStatisticItemsInDB()) {
session.delete(item);
}
session.flush();
assert numberOfStatisticRowsInDB() == 0;
}
#Test public void exportAllSavesEntriesToDatabase(){
int expectedNumberOfStatistics = 20;
dao.exportAll(StatisticItemFactory.createTestStatistics(expectedNumberOfStatistics));
assertEquals(expectedNumberOfStatistics, numberOfStatisticRowsInDB());
}
private int numberOfStatisticRowsInDB() {
return allStatisticItemsInDB().size();
}
#SuppressWarnings("unchecked")
private List<PersistableStatisticItem> allStatisticItemsInDB(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
transaction = session.beginTransaction();
Query q = session.createQuery("FROM PersistableStatisticItem item");
return q.list();
}
}
The console is filled with
Hibernate: delete from UPTIME_STATISTICS where logDate=? and serviceId=?
but nothing has been deleted when I check it.
I guess it's related to inconsistent use of transactions (note that beginTransaction() in allStatisticItemsInDB() is called several times without corresponding commits).
Try to manage transactions in proper way, for example, like this:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
for(PersistableStatisticItem item:
session.createQuery("FROM PersistableStatisticItem item").list()) {
session.delete(item);
}
session.flush();
assert session.createQuery("FROM PersistableStatisticItem item").list().size() == 0;
tx.commit();
See also:
13.2. Database transaction demarcation
I have the same problem. Although I was not using transaction at all. I was using namedQuery like this :
Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES);
int rows = query.executeUpdate();
session.close();
It was returning 2 rows but the database still had all the records. Then I wrap up the above code with this :
Transaction transaction = session.beginTransaction();
Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES);
int rows = query.executeUpdate();
transaction.commit();
session.close();
Then it started working fine. I was using SQL server. But I think if we use h2, above code (without transaction) will also work fine.
One more observation : To insert and get records usage of transaction is not mandatory but for deletion of records we will have to use transaction. (only tested in SQL server)
Can you post your DB schema and HBM or Fluent maps? One thing that got me a while back was I had a ReadOnly() in my Fluent map. It never threw an error and I too saw the "delete from blah where blahblah=..." in the logs.

Categories

Resources