开发者

Hibernate locking a arraylist of items

List <Student> st = session.createQuery ("select ids from students where a = :a")
              开发者_如何学Go          .setString("a", value)
                        .list();

//Errors out saying that ArrayList is an unknown entity
session.lock(st, LockMode.UPGRADE); 

Students itself extends Serializable. How do you lock an arraylist of serailizables in Hibernate?


You need to spin through the list and lock the entities one by one.

for(Student s : st) {
  session.lock(s, LockMode.UPGRADE);
}

NOTE: Session#lock(java.lang.Object, org.hibernate.LockMode) is deprecated in favor of session.buildLockRequest(LockMode.UPGRADE).lock(student)

UPDATE: You can also lock directly on the Query via Query.setLockMode(java.lang.String, org.hibernate.LockMode).


If you use JPA repository, then you can use the following sample:

import com.example.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.persistence.LockModeType;
import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Long> {

    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    @Query("select s from Student s where s.id IN (:ids)")
    List<Student> findByIdsAndLockForWrite(@Param("ids") List<Long> ids);

}

Please note that the service that calls this repository should use:
@Transactional(propagation = Propagation.REQUIRES_NEW)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜