Hibernate is not deleting my objects. Why? - java

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.

Related

How to delete data from mongodb v3.4 with hibernate ogm 5.1.0?

I am only able to retrieve data and insert data in mongo DB v 3.4 using Hibernate OGM 5.1.0.Final. I am not able to perform delete operation or update operations. Can anyone help me out with an example?
This question is a bit vague, I'm not sure if you know how to delete an entity with Hibernate OGM and it's not working (in this case post an example of your code, please) or you don't know how JPA works. I will assume you don't know how to delete entities and add some examples on how to do it.
Using the session:
try ( Session session = openSession() ) {
Transaction transaction = session.beginTransaction();
Hypothesis entity = (Hypothesis) session.get( Hypothesis.class, hyp.getId() );
session.delete( entity );
transaction.commit();
}
Using the EntityManager (JPA):
final EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
Poem poem = em.find( Poem.class, poem.getId() );
em.remove( poem );
em.getTransaction().commit();
}
finally {
em.close();
}
Using the MonogDB CLI API:
try ( OgmSession session = openSession() ) {
Transaction transaction = session.beginTransaction();
String nativeQuery = "db.Poem.remove({ '_id': { '$numberLong': '11' } })";
Query query = session.createNativeQuery( nativeQuery ).addEntity( Poem.class );
query.executeUpdate();
}
About updates, I will leave it to the Hibernate ORM documentation.
If this doesn't answer your question please, try to elaborate more. Test cases are always appreciated.

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...

How do I stop hibernate returning multiple instances when using "join" fetch mode?

Given the following I am trying to force the child collection (countryData) to be loaded when I perform the query, this works however I end up with duplicates of the Bin records loaded.
public Collection<Bin> getBinsByPromotion(String season, String promotion) {
final Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
return (List<Bin>) session.createCriteria(Bin.class).
setFetchMode("countryData", FetchMode.JOIN).
add(Restrictions.eq("key.seasonCode", season)).
add(Restrictions.eq("key.promotionCode", promotion)).
add(Restrictions.ne("status", "closed")).
list();
} finally {
session.getTransaction().commit();
}
}
I don't want the default (lazy) behavior as the query will return ~8k records thus sending 16k additional queries off to get the child records.
If nothing else I'd prefer.
select ... from bins b where b.seasonCode = ?
and b.promotionCode = ?
and b.status <> 'Closed';
select ... from binCountry bc where bc.seasonCode = ?
and bc.promotionCode = ?;
you can use CriteriaSpecification.DISTINCT_ROOT_ENTITY;
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

Categories

Resources