Когда нам следует использовать аннотацию @Transactional?JAVA

Программисты JAVA общаются здесь
Гость
Когда нам следует использовать аннотацию @Transactional?

Сообщение Гость »


Я хотел знать, когда нам следует использовать

Код: Выделить всё

@Transactional
in Spring Boot Services.
Since JpaRepository's method is annotated with

Код: Выделить всё

@Tranasactional
is it required for me to add that annotation in my service method?
I've seen a couple of articles saying that if there is only a repository being used inside your service method (like in the below scenario) then it's not required to put

Код: Выделить всё

@Transactional
on the service method as is already annotated with

Код: Выделить всё

@Transactional
. Is it true?

Код: Выделить всё

class EmployeeService {
@Autowired
EmployeeRepository repo;

@Transactional //(Is it required here?)
public void saveEmployee(Employee employee) {
repo.save(employee)
}
}
Should it be used in this below case on method

Код: Выделить всё

getStudentsWithNameStartsWithAndGradeLessThan()
since we are using more than one Repository?

Код: Выделить всё

@Getter
@Setter
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "name")
private String name;

@Column(name = "average_grade")
private Short averageGrade;
}

Код: Выделить всё

public interface StudentRepository extends JpaRepository {
Set findByAverageGradeLessThan(Short averageGrade);
Set findByNameStartsWithIgnoreCase(String name);
}

Код: Выделить всё

@Service
public class StudentService {

private final StudentRepository studentRepository;

public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}

@Transactional //(Is it required here?)
public Set getStudentsWithNameStartsWithAndGradeLessThan(String prefix, Short averageGrade) {

Set students = studentRepository.findByNameStartsWithIgnoreCase(prefix);
students.retainAll(studentRepository.findByAverageGradeLessThan(averageGrade));
return students;

}
}


Источник: https://stackoverflow.com/questions/781 ... annotation

Вернуться в «JAVA»