Now I have a class User, I get a request data of an array
from the jsp
or html
.
list this Integer[] arr=[5,6,9,10,62,52,21]
and then I use two methods to finish bulking deleting action.
@Transactional
@Override
public void deleteUser(Integer id) {
oneRepository.delete(id);
}
@Transactional
@Override
public void deleteSomeUser(Integer[] ids) {
for (Integer id : ids) {
deleteUser(id);
}
}
I want to know that if it's a more efficient method to finish this action.
you can see my logs: it seems not so good!
[94, 95, 91, 92, 93]
Hibernate:
delete
from
sshh_user
where
ID=?
Hibernate:
delete
from
sshh_user
where
ID=?
Hibernate:
delete
from
sshh_user
where
ID=?
Hibernate:
delete
from
sshh_user
where
ID=?
Hibernate:
delete
from
sshh_user
where
ID=?
Hibernate:
select
count(practice0_.ID) as col_0_0_
from
sshh_user practice0_
First of all you need to create a jpa query method that brings all records belong to id. After that you can do deleteAll() operation on List.
A derived delete query must start with deleteBy, followed by the name of the selection criteria. These criteria must be provided in the method call. The return value, of type long, indicates how many records the method deleted. Persisting and deleting objects in JPA requires a transaction.
To delete a record from database, EntityManager interface provides remove() method. The remove() method uses primary key to delete the particular record.
In JPA, to delete an entity, the entity itself must be managed, meaning that it is present in the persistence context. This means that the calling application should have already loaded or accessed the entity and is now issuing a command to remove it.
Just add the following to your user repository interface
void deleteByIdIn(List<Integer> ids);
Spring will automatically generate the appropriate query via method name derivation.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
EDIT: A litte more detail on this
Using Springs Repository interfaces like CrudRepository
, JpaRespository
brings the basic set of database operations, like create, read, update, delete, paging, sorting and so on.
To manually add some simple queries like searching for a users name or mail address spring provides a fine mechnanism without annotating any string based HQL queries or similar.
Spring just analyses your method names, searching for keywords. Read the documentation link above which keywords are provided.
Example methods for a CrudRepository<User>
:
Iterable<User> findByNameLike(String search)
resolves to select * from user where name like '<search>'
void deleteByIdIn(List<Integer> ids)
resolves to delete from user where id in ([ids])
UPDATE:
This will only work as a real bulk delete in Spring Boot Version < 2.0 !
Since Spring Boot 2.0 it will result in single delete queries to honour JPA Entity Lifecycle Events like preRemove
and postRemove
.
If you want to really bulk delete, please use the accepted answer.
Suppose you have a UserRepository
like:
public interface UserRepository extends JpaRepository<User, Integer> {}
Then you can add a modifying query method like following into your UserRepository
:
/**
* Delete all user with ids specified in {@code ids} parameter
*
* @param ids List of user ids
*/
@Modifying
@Query("delete from User u where u.id in ?1")
void deleteUsersWithIds(List<Integer> ids);
Finally you can change your bulk deletion service like following:
@Transactional
@Override
public void deleteSomeUser(Integer[] ids) {
oneRepository.deleteUsersWithIds(Arrays.asList(ids));
}
This will generate a delete query like:
Hibernate: delete from users where id in (? , ? , ?)
Also be aware of Self Invocation issues when you calling one public
advised method from another one.
You can use different method for deleteAll item list without call repository twice. When deleteAll method call, CrudRepository or JpaRepository look just objects id.
List<User> userList = userIdList.stream().map(id -> {
User user = new User();
user.setId(id);
return user;
}).collect(Collectors.toList());
userRepository.deleteAll(userList);
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