I want to delete multiple records of a certain entity where the id of the entity is in the list of ids I have. I am trying to perform this action in C# with NHibernate.
What I have is a list of Ids.
I want to do something similar to this :
var idList = new List<Guid>() { Guid.NewGuid(),Guid.NewGuid()};
_session.CreateQuery("DELETE FROM MapsItem o WHERE o.Id = IN :idList")
.SetParameterList("idList", idList)
.ExecuteUpdate();
This results into the following error :
Exception of type 'Antlr.Runtime.NoViableAltException' was thrown. near line 1, column 33 [DELETE FROM Album o WHERE o.Id = IN :idList]
The query is a HQL statement.
What is wrong in the HQL query.
Both of the provided answers to the above question give a correct solution. However, when I execute the HQL,the error is like this:
could not insert/select ids for bulk delete[SQL: insert into #MapsItem SELECT mapsitem0_.Id as Id FROM MapsItem mapsitem0_ inner join BaseEntity mapsitem0_1_ on mapsitem0_.Id=mapsitem0_1_.Id WHERE Id in (? , ? , ? , ? , ? , ?)]
The entity MapsItem derives from the entity BaseEntity. Both have a property Id in the database. The SQL query cannot be executed, because the column Id in the WHERE clause is ambigious.
How can I solve this problem ?
HQL delete query is as same as the update. The HQL delete is used to delete the bulk records from the database. If our requirement is to delete a single record, we can go with hibernate delete operation. HQL Delete Query Examples :
You can, of course, use other conditions/columns as well. Using the IN clause, we can specify multiple row ids to delete. For example, the following query would delete rows with ids equal to 1, 5 and 7 :
For selective multiple records, use MySQL IN (). To delete them, use MySQL DELETE. Let us first create a table −
That requires at least 1 query to load all entities and an additional SQL DELETE statement for each of them. So, when you use this approach to remove 100 entities, Hibernate has to perform at least 101 SQL statements. It’s often better to remove such a list of entities with a JPQL query.
Remove the equal sign:
DELETE FROM myObject o WHERE o.Id IN :idList
Delete the equals to sign and also your inquery is incorrect. It should be something like this. and i would suggest you to use string.Format instead.
var idList = new List<Guid>() { Guid.NewGuid(),Guid.NewGuid()};
_session.CreateQuery(string.Format("DELETE FROM myObject o WHERE o.Id IN
({0})",string.Join(",",idList.ToArray()))).ExecuteUpdate();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With