Home > Software engineering >  Problem with one-to-many in Spring Boot project
Problem with one-to-many in Spring Boot project

Time:07-28

i have these two class below: product and category, as you can see there is a bidirectional one-to-many relationship. evertithing works but the application throws me the error i posted below and i don't know why.

@Entity(name = "product")
@Table(name = "product",
        uniqueConstraints = @UniqueConstraint(name = "unique_eancode_constraint", columnNames = "ean_code")
)

@Getter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Setter
public class ProductModel {
    @Id
    @SequenceGenerator(
            name="product_sequence",
            sequenceName = "product_sequence",
            initialValue = 0,
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "product_sequence"
    )
    private Long id;
    @Column(
            name = "ean_code",
            nullable = false,
            updatable = false,
            columnDefinition = "VARCHAR(13)"
    )
    private String eanCode;
    @Column(
            name = "product_name",
            nullable = false,
            updatable = false,
            columnDefinition = "VARCHAR(100)"

    )
    private String name;
    @Column(
            name = "price",
            nullable = false

    )
    private BigDecimal price;
    @Column(
            name = "quantity",
            nullable = false

    )
    private Integer quantity;
    @Column(
            name = "weight",
            nullable = false,
            updatable = false,
            scale = 3
    )
    private Double weight;
    @Column(
            name = "description",
            columnDefinition = "TEXT"
    )
    private String description;
    @ManyToOne
    private CategoryModel category;


    public ProductModel(String eanCode,
                        String name,
                        BigDecimal price,
                        Integer quantity,
                        Double weight,
                        String description,
                        CategoryModel categoryModel) {
        this.eanCode = eanCode;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
        this.weight = weight;
        this.description = description;
        this.category = categoryModel;
    }



        public ProductModel(String eanCode, String name, BigDecimal price, Integer quantity, Double weight, String description) {
            this.eanCode = eanCode;
            this.name = name;
            this.price = price;
            this.quantity = quantity;
            this.weight = weight;
            this.description = description;
        }
    
    
        public ProductModel(ProductDTO productDTO) {
            this.eanCode = productDTO.getEancode();
            this.name = productDTO.getName();
            this.price = productDTO.getPrice();
            this.quantity = productDTO.getQuantity();
            this.weight = productDTO.getWeight();
            this.description = productDTO.getDescription();
        }

}

  @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    @Getter
    @Setter
    @Entity(name = "category")
    @Table(name = "category",
            uniqueConstraints = @UniqueConstraint(name = "unique_name_constraint", columnNames = "category_name")
    )
    public class CategoryModel {
        @Id
        @SequenceGenerator(name = "category_sequence",
                sequenceName = "category_sequence",
                initialValue = 0,
                allocationSize = 1
        )
        @GeneratedValue(strategy = GenerationType.SEQUENCE,
                generator = "category_sequence"
        )
        private Long id;
        @Column(name = "category_name",
                nullable = false
        )
        private String name;
        @OneToMany(cascade = CascadeType.ALL,
               mappedBy = "category",
                orphanRemoval = true
        )
        private Set<ProductModel> products;
    
        public CategoryModel(String name) {
            this.name = name;
        }
    
        public void addProduct(ProductModel productModel){
            if(this.products == null) products = new HashSet<>();
            this.products.add(productModel);
            productModel.setCategory(this);
        }
    /*
        public void removeProduct(ProductModel productModel){
            this.products.remove(productModel);
            productModel.setCategory(null);
        }
    */
    }

this is the error. there are no other tables in the db (i'm using mySQL) which the same names.

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table product drop foreign key FK1mtsbur82frn64de7balymq9s" via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]

CodePudding user response:

  1. One sugestions is your config into "ProductModel "

     @JoinColumn(name = "fk_category") // @JoinColumn(name = "category_id")
     private CategoryModel category;
    
    
    
    
  2. Then do maping into "CategoryModel" to use foreign key column instead of an association table to map the relationship.

    @JoinColumn(name = "fk_category")        
    private Set<ProductModel> products;
    
    
  3. But if you intend to use "CategoryModel" for more than one products is necessary reviewer your maping

Reference: https://thorben-janssen.com/best-practices-many-one-one-many-associations-mappings/

CodePudding user response:

PeterMmmm wrote the answer to this problem: How to fix "Error executing DDL "alter table events drop foreign key FKg0mkvgsqn8584qoql6a2rxheq" via JDBC Statement"

  • Related