Hibernate Delete object by id

Which method is best for deleting an object if only its identifier is available.

  • Hql

    . Will running this HQL load the SessionContext into the hibernate save context?

    for(int i=0; i<listOfIds.size(); i++){
        Query q = createQuery("delete from session_context where id = :id ");
            q.setLong("id", id);
            q.executeUpdate();
    }
    
  • Download by ID and delete.

    for(int i=0; i<listOfIds.size(); i++){
        SessionContext session_context = (SessionContext)getHibernateTemplate().load(SessionContext.class, listOfIds.get(i));
        getHibernateTemplate().delete(session_context) ;
    }
    

Here, SessionContext is the object mapped to the session_context table. Or, of course, are there all different and better approaches?

+5
source share
3 answers

Of the first two, it’s better when you save your memory. If you want to remove Entity and you have an identifier with you, it is recommended to write HQL.

In your case, there is a third and best option,

Try below

//constructs the list of ids using String buffer, by iterating the List.
String idList = "1,2,3,....."

Query q = createQuery("delete from session_context where id in (:idList) ");
q.setString("idList", idList);
q.executeUpdate();

Now, if there are 4 items in the list, only one request will be launched. It would be 4 before.

. - , session_context .

+7

Btw, , .setParameterList(), :

List<Long> idList = Arrays.asList(1L, 2L, 3L);

Query q = createQuery("delete from session_context where id in (:idList) ");
q.setParameterList("idList", idList);
q.executeUpdate();

, , , , setParameterList , setString, , @ManuPK.

+3

- () .

, , , .

SessionContext, HQL , , hibernate , . .

, , SessionContext.

+2

All Articles