无法使用存储库持久化会话范围bean实体

gojuced7  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(311)

我正试图将会话范围内的购物车持久化到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;
ghg1uchk

ghg1uchk1#

使用一对一Map和关联两侧的引用,尝试将用户与行一起设置在购物车中

user.setCart(cart);
cart.setUser(user);

如果存在外键约束,则可能需要在此时删除已持久化的购物车。另外,外键上的非空约束可能会影响清理方式。

相关问题