我正试图将会话范围内的购物车持久化到hibernate中,但我似乎无法做到这一点,因为db中持久化的购物车与会话中的购物车不同,有没有办法解决这个问题?
@SessionScope
@Service
public class AuthSuccessHandler implements AuthenticationSuccessHandler {
@Autowired
private Cart cart;
@Autowired
private UserRepository userRepository;
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException, ServletException {
User user = (User) authentication.getPrincipal();
HttpSession session = httpServletRequest.getSession();
user.setCart(cart);
System.out.println(cart.getTest());
// shopping cart is not the same as the autowired one
userRepository.saveAndFlush(user);
System.out.println(cart.getTotal());
}
}
用户类
@Entity
public class User implements UserDetails, Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(cascade=CascadeType.ALL)
private Cart cart;
购物车类
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
@Entity
public class Cart implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "cart", cascade = CascadeType.ALL)
private List<CartItem> cartItems;
@OneToOne(mappedBy = "cart")
private User user;
private long test;
1条答案
按热度按时间ghg1uchk1#
使用一对一Map和关联两侧的引用,尝试将用户与行一起设置在购物车中
如果存在外键约束,则可能需要在此时删除已持久化的购物车。另外,外键上的非空约束可能会影响清理方式。