【问题标题】:Cannot persist session scope bean entity using repository无法使用存储库持久化会话范围 bean 实体
【发布时间】:2021-06-05 13:45:00
【问题描述】:

我正在尝试将会话范围的购物车持久化到休眠状态,但我似乎无法这样做,因为数据库中持久化的购物车与会话中的购物车不同,有没有办法解决这个问题?

@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;

【问题讨论】:

    标签: spring spring-boot hibernate jpa session


    【解决方案1】:

    通过一对一映射和关联两侧的引用,尝试将用户与您的行一起设置在购物车中

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

    如果您有外键约束,那么此时可能需要删除已经持久化的购物车。此外,外键的非空约束可能会影响您的清理方式。

    【讨论】:

    • 感谢您的回答。事实证明,我没有直接持久化会话购物车,而是创建了一个新的购物车并将其持久化。
    猜你喜欢
    • 1970-01-01
    • 2013-12-30
    • 2013-08-02
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2018-08-09
    • 2016-01-31
    • 1970-01-01
    相关资源
    最近更新 更多