У меня проблема с ленивой инициализацией в приложении Spring Boot. У меня есть объект с ленивым полем Role
, и у меня есть LazyInitializationException
в методе My Spring Security (UserDetailsService
), но в контроллере это нормально. Можете ли вы объяснить мне, как работает Spring Boot с fetch = FetchType.LAZY
? Почему это не работает Spring Security UserDetailsService
и работает в методах контроллера? Я не нашел гида об этом. Благодаря!Spring Boot и fetchType = Lazy
Spring Ботинок:
@SpringBootApplication
public class App {
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
Субъект:
@Entity
@Table(name = "users")
@Getter
@Setter
@NoArgsConstructor
public class Users {
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "Users_Role", joinColumns = @JoinColumn(name = "User_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles = new HashSet<Role>();
}
Моя_служба:
@Transactional(readOnly = true)//does not matter
public Users getUserByLogin(String login) {
return usersRepository.findOneByLogin(login);
}
@Transactional(readOnly = true)
public Users getUserByLoginWithRoles(String login) {
Users oneByLogin = usersRepository.findOneByLogin(login);
logger.debug("User was initialize with Roles: " + oneByLogin.getRoles().size()); // force initialize of roles and it works!
return oneByLogin;
}
@Transactional(readOnly = true)//does not matter
public Users testGetUser() {
Users oneByLogin = usersRepository.getOne(1L);
return oneByLogin;
}
@Transactional(readOnly = true)//does not matter
public Users testFindUser() {
Users oneByLogin = usersRepository.findOne(1L);
return oneByLogin;
}
И у меня есть Spring Security UserDetailsService:
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private Services services;
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
Users user;
Users userFetchedViaGet = services.testGetUser();
Users userFetchedViaCustomMethod = services.getUserByLogin(login);
Users userFetchedViaFind = services.testFindUser();
Users userFetchedWithRoles = services.getUserByLoginWithRoles(login);
try {
userFetchedViaGet.getRoles().add(new Role("test"));
} catch (Exception e) {
e.printStackTrace();//LazyInitializationException: failed to lazily initialize a collection of role: , could not initialize proxy - no Session
}
try {
userFetchedViaCustomMethod.getRoles().add(new Role("test"));
} catch (Exception e) {
e.printStackTrace();//LazyInitializationException: failed to lazily initialize a collection of role: , could not initialize proxy - no Session
}
try {
userFetchedViaFind.getRoles().add(new Role("test")); //LazyInitializationException: failed to lazily initialize a collection of role: , could not initialize proxy - no Session
} catch (Exception e) {
e.printStackTrace();
}
//some code
}
}
И мой контроллер (все методы работают! Но есть должна excpetion произойти, потому что нет сеанса и Ленивых выборки типа):
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
Users userFetchedViaGet = services.testGetUser();
Users userFetchedViaCustomMethod = services.getUserByLogin("ADMIN");
Users userFetchedViaFind = services.testFindUser();
Users userFetchedWithRoles = services.getUserByLoginWithRoles("ADMIN");
try {
userFetchedViaGet.getRoles().add(new Role("test"));
} catch (Exception e) {
e.printStackTrace();
}
try {
userFetchedViaCustomMethod.getRoles().add(new Role("test"));
} catch (Exception e) {
e.printStackTrace();
}
try {
userFetchedViaFind.getRoles().add(new Role("test"));
} catch (Exception e) {
e.printStackTrace();
}
//some code
}
Вы пробовали это http://stackoverflow.com/questions/11746499/solve-failed-to-lazily-initialize-a-collection-of-role-exception –
Здравствуйте! Этот пост не имеет ничего общего с моим вопросом. –
Могли бы вы решить это? У меня на самом деле такая же проблема –