Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

java - Why CrudRepository.save() ignore FetchType.EAGER when returning created object?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

save() just delegates to EntityManager.persist or EntityManager.merge and returns the object returned by EntityManager.merge or the one you passed in. The FetchType does not play a role here. If you want the association to be loaded, you can use refresh or findOne.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...