Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...