I use Spring Data Jpa in my app. There are two entities in the application. The entity Film
:
//annotations omitted
public class Film {
// other annotations omitted
@ManyToMany(fetch = FetchType.EAGER)
private List<User> users;
...
and User
:
//annotations omitted
public class User {
// other annotations omitted
@ManyToMany(fetch = FetchType.LAZY)
private List<Film> films;
...
And DTO for Film
:
public class FilmTo implements Serializable {
private List<Integer> userIds; // i using users ids instead of users for simplify REST-requests
}
And the app has repositories classes:
@Transactional(readOnly = true)
public interface CrudFilmRepository extends JpaRepository<Film, Integer> {
}
@Transactional(readOnly = true)
public interface CrudUserRepository extends JpaRepository<User, Integer> {
}
Ok. This code using, when i want to save new film:
@Service
public class FilmService {
@Autowired
private CrudFilmRepository repository;
@Autowired
private CrudUserRepository userRepository;
public Film save(FilmTo filmTo) {
Film film = new Film();
film.setUsers(Arrays.stream(filmTo.getUserIds())
.map(crudUserRepository::getOne)
.collect(Collectors.toList()));
return repository.save(film);
}
The problems occurs when save() returns created Film, and i want works with users in List in returned Films. Throws LazyInitializationException even if User list <User>
is marked as FetchType.EAGER!
Why crudRepository ignore FetchType.EAGER, when i use users lazy references for initialize new Film and try save this film?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…