Hibernate Session.delete() an object if exists

前端 未结 7 1806
谎友^
谎友^ 2020-12-31 03:41

In JavaDoc of Session class the description of delete method is:

Remove a persistent instance from the datastore. The argument may be

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 04:02

    or a transient instance with an identifier associated with existing persistent state

    This means you can directly pass your entity to session.delete(), in order to delete that object. Further, you need not check whether the entity exist or not. There should be an exception if no record found in the database. In fact, we usually don't really get this case. We always delete an existing entity, I mean usual logic is like that; so, no need to do that. You can simply do this,

    SomeEntity ent = session.load(SomeEntity.class, '1234');
    session.delete(ent);
    

    or you can do this instead,

    SomeEntity ent = new SomeEntity('1234'); // used constructor for brevity
    session.delete(ent);
    

    Btw, you can also use this version session.delete(String query),

    sess.delete("from Employee e where e.id = '1234'"); // Just found it is deprecated
    

提交回复
热议问题