Hibernate query performance in order to delete an object
I am developpng a simple web service: void deleteCar(int idCar)
Currently, what I am doing in my code is :
1 - load the car Object by id :session.get(Car.class,idCar) 2 - remove it : session.delete(carLoaded)So for an operation I have at least 2 sql query (n+1 problem ?)
I don't even speak about any not lazy relationship in the car that will result in more SQL queries.I thought that to use an HQL query:
1 - will check by the id if the car exist with a lockMode.UPGRADE (boolean carDao.exist(int id)) 2 - if the car exist, use a hql query like this one :"delet from Car c wher开发者_如何学Ce c.id=?"But how the cache might react to this (we will use ehCache)
In the first solution, I'm almost sure the car will be evicted from the 2nd level cache.
In the 2nd solution( with hql query), will the cache be smart enough to remove the car loaded in the 2nd level cache?
So for an operation i have at least 2 sql query (n+1 problem ?)
The N+1 problem occurs when you retrieve N entities (with 1 query) and need to perform an additional query per entity (N in total) to fetch something. That's not really the case here.
I don't even speak about any not lazy relationship in the car that will result in more sql queries.
Well, if you have a graph of objects, you'll need several delete queries. Aren't you happy that Hibernate can cascade them for you?
I have thought to use an HQL query that (...)
Firstly, I don't really see the point of the first select (I thought you wanted to limit the number of queries).
Secondly, a bulk HQL DELETE
would indeed save a SELECT
but it doesn't cascade to related entities which might be a problem in your case (so you'll have to handle relations yourself, if possible).
Not sure it will suit your needs.
But how the cache might react to this
Hibernate will invalidate needed region(s) upon completion of a "bulk Operation".
See Bulk Operations for details and recommendation about their use.
精彩评论