我有一個關於@Transactional註釋的問題。 沒有什麼特別的定義,所以據我所知PROPAGATION_REQUIRED 假設我有一個在服務和dao層上的事務註釋。交易在服務和道服務層
服務
@Transactional
public long createStudentInDB(Student student) {
final long id = addStudentToDB (student);
addStudentToCourses (id, student.getCourseIds());
return id;
}
private long addStudentToDB (Student student) {
StudentEntity entity = new StudentEntity();
convertToEntity(student, entity);
try {
final id = dao.create(entity);
} catch (Exception e){
//
}
return id;
}
private void addStudentToCourses (long studentId, List<String> coursesIds){
//add user to group
if(coursesIds!= null){
List<StudentCourseEntity> studentCourses = new ArrayList<>();
for(String coursesId: coursesIds){
StudentCourseEntity entity = new StudentCourseEntity();
entity.setCourseId(coursesId);
entity.setStudentId(userId);
studentCourses.add(studentId);
}
anotherDao.saveAll(studentCourses);
}
}
DAO
@Transactional
public UUID create(StudentEntity entity) {
if (entity == null) { throw new Exception(//…); }
getCurrentSession().save(entity);
return entity.getId();
}
ANOTHERDAO
@Transactional
public void saveAll(Collection<StudentCourseEntity> studentCourses) {
List<StudentCourseEntity> result = new ArrayList<>();
if(studentCourses!= null) {
for (StudentCourseEntity studentCourse : studentCourses) {
if (studentCourse!= null) {
save(studentCourse);
}
}
}
}
儘管這不是最優的事實,現在看來,這導致死鎖。 假設我有最多2個連接到數據庫。 而我正在使用3個不同的線程來運行相同的代碼。 線程1和線程2接收連接,線程3沒有獲得任何連接。 除此之外,看起來thread-1在嘗試獲取dao級別的連接時變得卡住,與thread-2相同。造成僵局。
我確信通過使用propagation_required這不會發生。 我錯過了什麼嗎? 這是什麼建議?有沒有一種方法可以在兩個層上都有@transactional?如果不是哪個是首選? 感謝 法布里奇奧
如果您的連接不夠用,您可能沒有正確設置事務,或者自己搞亂連接,而不是讓Spring管理事務。只有在沒有實現的情況下添加方法簽名才能解決您的問題。首先檢查你的設置(確保你有正確的tx設置)並檢查你的實現。 –