How to delete multiple db entities with Nhibernate?

可紊 提交于 2019-12-20 12:26:32

问题


What is the best practice for this problem? Is there any batching features built-in?

Sample code:

using (ITransaction transaction = _session.BeginTransaction())
{
   _session.Delete("FROM myObject o WHERE  o.Id = IN(1,2,...99999)");
   transaction.Commit();
}

Thanks in advance.


回答1:


HQL supports the IN clause, and if you use setParameterList you can even pass in a collection.

var idList = new List<int>() { 5,3,6,7 };

_session.CreateQuery("DELETE MyDataClass o WHERE o.Id IN (:idList)")
    .SetParameterList("idList", idList)
    .ExecuteUpdate();

Be aware, like mentioned by ddango in a comment, that relationship cascades specified in your objects will not be executed since running an HQL query simply translates to a DB query and does not actually load any entity objects.




回答2:


I had problems getting the answer to work and I found the following query worked 100%

        Session.CreateQuery("delete Customer c where c.id in (:deleteIds)")
            .SetParameterList("deleteIds", deleteIds)
            .ExecuteUpdate();

Customer is the class name not the table name. id is lowercase and in HQL it is the Primary Key not a property name in the class (Property names are supported)




回答3:


you can Use HQL to delete multiple objects

Look for delete here - for session.delete example

HQL DELETE example (you can use IN with HQL):

ISession session = sessionFactory.OpenSession();
ITransaction tx = session.BeginTransaction();

String hqlDelete = "delete Customer c where c.name = :oldName";
// or String hqlDelete = "delete Customer where name = :oldName";
int deletedEntities = session.CreateQuery( hqlDelete )
        .SetString( "oldName", oldName )
        .ExecuteUpdate();
tx.Commit();
session.Close();


来源:https://stackoverflow.com/questions/1869057/how-to-delete-multiple-db-entities-with-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!