我有一个关于@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设置)并检查你的实现。 –