Garmaine Staff asked 2 years ago

I'm learning Spring and few days ago i started learning Hibernate. I have my studying project where i need to create a shop with products. Here is entity class

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Entity
@Table(name = "cart")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Cart {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")

    private int id;
    @Column(name = "quantity")
    private int quantity;
    @Column(name = "mask")
    private String mask;
    @Column(name = "price")
    private int price;

So, i create interface

import org.springframework.data.jpa.repository.JpaRepository;

public interface CartRepository extends JpaRepository<Cart, Integer> {
}

and create controllers

@Autowired
    CartRepository cartList;

    @RequestMapping("/add-black-mask")
    public String addBlackMask() {
        cartList.save(new Cart(1, 1, "black", 3));

        return "masks/add-black-mask";
    }

    @RequestMapping("/add-build-mask")
    public String addBuildMask() {
        cartList.save(new Cart(2, 1, "build", 5));

        return "masks/add-build-mask";
    }


  @RequestMapping(value = "/save_product_to_cart")
    public ModelAndView saveProduct(@ModelAttribute(value = "cart")
                                            Cart cart, BindingResult result) {
        int index = Integer.parseInt(String.valueOf(cartList.count()));
        if (cart.getId() == 0) {
            cart.setId(index + 1);
            cartList.save(cart);
        } else {
            Cart cart1 = cartList.getOne(cart.getId());
            cart1.setMask(cart.getMask());
            cart1.setQuantity(cart.getQuantity());
            cart1.setPrice(cart.getPrice());
            cartList.save(cart1);
        }
        return new ModelAndView("redirect:/");
    }

Also, there are some other controllers for view, Thymeleaf etc, but its ok. My problem is – when i save my product 1 time – its ok, but when i save second – it didnt work( i think because i can't save 2 rows with similar ID) So it seems i have UNIQUE ID in my table and it can not be repeated. Question is – how can i delete unique id or change my code in any way? Thanks in advance!

p.s. i read some other topics here but it didnt help me.