如何防止购物车中的重复商品?

时间:2016-04-13 15:46:31

标签: java spring jpa

对于数据库的当前结构:

database structure

用户

@Entity
@Table(name = "users")
public class User {

    @Id
    @Column(name = "username", unique = true, nullable = false, length = 45)
    private String username;
    @Column(name = "password", nullable = false, length = 60)
    private String password;
    @Column(name = "enabled", nullable = false)
    private boolean enabled;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade=CascadeType.ALL)
    private Set<UserRole> userRole = new HashSet<UserRole>(0);

    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(
            name = "users_product",
            joinColumns ={@JoinColumn (name = "users_username",  referencedColumnName = "username")},
            inverseJoinColumns = {@JoinColumn(name = "Products_idProducts", referencedColumnName = "idProducts")}
    )
    List<Products> productsList = new ArrayList<Products>();

产品

@Entity
@Table(name = "products")
public class Products implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idProducts")
    private long id;

    @Column(name = "description")
    private String description;

    @Column(name = "price")
    private String price;

    @Column(name = "image")
    private byte [] image;

    @ManyToMany(mappedBy = "productsList")
    List<User> usersList = new ArrayList<User>();

//setters - getters

我想实现一个购物篮。

我现在拥有的内容:视图页面上包含产品和复选框的页面。我找到这些产品并将它们发送到我的控制器,然后将它们设置为当前用户。

productsList = myService.findManyProducts(toAdd);
            user.setProductsList(productsList);
            myService.updateUser(user);


@Transactional
public void updateUser(User user){
    userDao.update(user);
}

更新用户功能:

@Override
public void update(User user) {
    entityManager.merge(user);
}

这些操作在数据库中作为不同的值输入,具体取决于最新添加的内容。

我想要的是什么: 用户将一些产品添加到购物车,浏览其他项目,并将新产品添加到购物车。如何确保购物车中找不到重复的商品? JPA有一些标准方法吗?或者,在将它们添加到数据库之前,我是否需要自己检查产品列表?

0 个答案:

没有答案