gpt4 book ai didi

java - 未能延迟实例化 HashMap

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:36 25 4
gpt4 key购买 nike

我有下一个错误:

请求处理失败;嵌套异常是 org.hibernate.LazyInitializationException:无法延迟初始化角色集合:my.shop.common.fliPusto.origins.User.spectatingBooks,无法初始化代理 - 无 session

我尝试使用 Hibernate.initialize()myObject.getMyMap().size() 初始化 Map,但它们都抛出异常。

我的 HashMap 类:

@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

...

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "spectatingBooks", joinColumns = @JoinColumn(name =
"user_id"))
@MapKeyJoinColumn(name = "book_id")
@Column(name = "lastChapter")
private Map<Book, Long> spectatingBooks = new HashMap<Book, Long>();
}

当我将获取类型从 Lazy 更改为 Eager 时,一切正常,但我认为这是错误的方式。

我的类(class)试图添加一些书籍:

@Transactional
@Service
public class UserDetailsServiceImpl implements UserDetailsService,
UserDetailsServiceImplInterface {

...

@Transactional
public Boolean addBookmark(User user, Long bookId) {
Optional<Book> book = bookRepository.findById(bookId);

if (book.isPresent()) {
Hibernate.initialize(user);
int size = user.getSpectatingBooks().size(); <--Exception
user.getSpectatingBooks().put(book.get(),
Integer.toUnsignedLong(0));
userRepository.save(user);
return true;
}

return false;
}
}

是否存在任何方法可以延迟实例化 HashMap 或者它只能与 Fetch.Eager 一起使用?

最佳答案

我通过userRepository而不是@AuthenticationPrinciple让用户解决了这个问题,但也许还存在另一种方式?

@Transactional
public Boolean addBookmark(Long userId, Long bookId) {
Optional<Book> book = bookRepository.findById(bookId);
Optional<User> userOp = userRepository.findById(userId);

if (book.isPresent() && userOp.isPresent()) {
User user = userOp.get();
int size = user.getSpectatingBooks().size();
user.getSpectatingBooks().put(book.get(), Integer.toUnsignedLong(0));
userRepository.save(user);
return true;
}

return false;
}

关于java - 未能延迟实例化 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55463576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com