Getting the deleted record? - java

I am using hibernate. i am deleting record using delete method as below.
Session session = sessionFactory.getCurrentSession();
session.delete(pojotobedeleted);
my requirement is after deleting the record, it should return the same deleted record. How can i get the deleted record?
Thanks!

I'd say
Session session = sessionFactory.getCurrentSession();
pojotobedeleted = session.load(Pojo.class, id); /* not necessary if loaded before */
session.delete(pojotobedeleted);
return pojotobedeleted;
Sure there is an extra select statement for doing so, but that is the same with native SQL. The SQL delete does not return the deleted rows, and hibernate can't be better that native SQL.
(If this is not what you wants then I don't understand your question: What is the goal, why not like in my example?)

Related

Saving the entity outside the transaction

I have the below code which tries to save the entity outside the transaction:
Session session = HibernateUtil.buildSessionFactory().openSession();
Teacher t= new Teacher();
t.setName("jonathan");
session.save(t);
session.flush();
According to the definition of save() if used outside the transaction we need to do flush() to save the entity in the db.However the above code does not save it. I have to create a transaction and commit it in order to add a row in db. Why is this so?
I am using HIbernate 4.3.6
EDIT: I just noticed that the session.save() returns the id but only after transaction.commit() the row is added.The other question does not answer my question.Since this basically means that save() in order to add the row in db has to be in a transaction only

Entity can still be selected after deleted by hibernate in transaction

I have a method to delete record by hibernate. I add a query after deletion. And the record deleted is still in the result list. It should not be. Here is the code.
#Transactional
public void deleteFoo(long fooId){
Foo foo = fooDao.find(fooId);
fooDao.delete(foor);
List<Foo> brothers = fooDao.findByParentId(foo.getParentId());
// I think the brothers does not contains foo.
// Unfortunately, foo is still in the list.
// I do not know why and how to make sure the brothers does not contains foo.
...
}
The record is deleted from database where the transaction committed.
You should flush the hibernate session.
When your work with database via Hibernate you are using Hibernate session.
Hibernate sessions flushed to the database by following three situations.
commit()- When you commit a transaction
Before you run a query
When you call session.flush()
or you can flush it manually by
session.flush()

Hibernate batch update using HQL Query

I'm using Hibernate for my ORM layer.
I'm try to run batch of HQL queries in one transaction (I cannot use session.update).
The issue is that even the transaction.commit() is at the end of the loop, the update queries run one by one.
Is there a way to run multiple HQL queries in one transaction?
public void updateItems() {
t = session.beginTransaction();
for (int i = 0; i < itemList.size(); i++) {
Query q = createUpdateQuery(session, itemList.get(i));
q.executeUpdate(); //updating one by one, and not waiting for transaction commit
}
t.commit();
}
Query createUpdateQuery(Session session, Item item) {
Query q = session.createQuery(
"Update Item i set i.notes=:notes, i.time=:time, i.counter=:counter, i.status=:status Where i.id=:id and i.time=:time");
q.setParameter("time", item.getTime());
q.setParameter("status", item.getStatus());
q.setParameter("notes", item.getNotes());
q.setParameter("id", item.getId());
return q;
}
Appreciate any help.
You are using a database transaction to enroll all your statements, but I think you want to use batch updates.
Just add the following configuration property:
<property name="hibernate.jdbc.batch_size" value="10"/>
Even so, I think you should use Hibernate to manage the insert/update/delete statements, as you should only focus on entity state transitions. The dirty checking mechanism can automatically detect entities that have been modified, and Hibernate can generate the update statement for you, which is much more convenient.

Querying Hibernate cache

I have the following code:
Person a = new Person();
a.setName("John");
Session session = openHibernateSession();
session.beginTransaction();
session.saveOrUpdate(a);
Criteria critera = session.createCriteria(Person.class);
critera.add(Restrictions.eq("name","John"));
Person personFromCache = (Person) criteria.uniqueResult();
...
session.commit();
What I want is to have the ability to search objects from both the database and Hibernate's cache. The following example returns null upon calling uniqueResult. Is there any way to retrieve saved objects that have not yet been committed to the database?
If you are searching other than ID then Hibernate will not use first level cache. Hibernate get and load is related to first level cache by default but criteria query is not. In your case there are two solution from my side
By flushing session = Just flush your session like this session.flush(); while doing so data from session will be synchronize to database hence Id will ge generated and as result Criteria query will find the result in database and will result list to you.
Enable hibernate second level cache = You can enable second level cache by hibernate cache providers like ehCache and apply the trick.
You can use the StatelessSession but be warned:
those entitys are not bound to any session and you will get Exceptions if you like to resolve relations or lazy fields!
session.beginTransaction();
session.saveOrUpdate(a);
session.flush();
Criteria critera = session.createCriteria(Person.class);
critera.add(Restrictions.eq("name","John"));
Person personFromCache = (Person) criteria.uniqueResult();
We do some similar things except using TestNg test framework. Several of the answers discuss the session.flush() method call. This is correct. The call to flush tells Hibernate to do several things, including making sure that all database calls currently waiting in the queue get executed and cleared from the queue.
It returns data even if you are selecting on the basis of username. It is not returning null.

Update specific field of table regardless of other fields in hibernate

I have table having lot of information. I am not loading all the information while updating this table from view page.
Below is my code to update the table using hibernate
HibernateTemplate hibernateTemplateObj = getHibernateTemplate();
hibernateTemplateObj.update(myEntityBean);
Above one was updating the fields but the fields which are not visible on my view page will be updated with blank.
So, I used below one...
HibernateTemplate hibernateTemplateObj = getHibernateTemplate();
hibernateTemplateObj.update("myRequiredField", myEntityBean);
As per documentation here it says if I use update("string",entity) it will update that fields. But it's not working as same.
Can any one please suggest something.
I found some posts.
post1
post2
It says, I need to create queries. But I don't know how to create queries from it?
If any one have any idea.. Please help. I think it's known issue from those posts.
You can create a query with the Session object like this.
SessionFactory factory= HibernateUtil.getSessionFactory();
session = factory.openSession();
session.beginTransaction();
Query query = session.createQuery("Select c.productList from Cart c Where c.cartId=:cartId");
query.setParameter("cartId", cart.getCartId());
List productList=(List) query.list();
session.getTransaction().commit();
While you know what kind of object should return from query you can cast it and use it.
You can write native query or hibernate query but I think hibernate query is easier.

Categories