F
F
Fedor unknown2021-09-13 07:24:57
Java
Fedor unknown, 2021-09-13 07:24:57

How to link two relationships correctly in java?

I have three tables that have a ManyToMany relationship:
1. product
2. category
3. product_category (intermediate table)

@Entity
@Table(name = "category")
@Data
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    private String description;

    @ManyToMany(mappedBy = "category")
    private List<Product> productList;
}


@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;
  private String description;
  private String category;
  private int price;


  @ManyToMany(fetch = FetchType.EAGER)
  @JoinTable(name = "product_categories",
        joinColumns = @JoinColumn(name = "product_id"),
        inverseJoinColumns = @JoinColumn(name = "category_id"))
  private List<Category> categoryList;	
}


create table prouct_categories(
product_id BIGINT REFERENCES product(id),
category_id BIGINT REFERENCES category(id)
);


Problem:
When adding data to Category table
, throws error: org.postgresql.util.PSQLException: ERROR: NULL value in column "id" of relation "category" violates NOT NULL constraint

Question: what could be wrong? How to properly link two tables?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-09-14
@turdubekov

I will answer based on your second question , to which I already wrote an answer:

@Entity
@Table(name = "category")
@Data
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @Column(length = 1000)
    private String description;

    @ManyToMany(mappedBy = "categoryList")
    private List<Product> productList;
}

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;

  @Column(length = 1000)
  private String description;

  private double price;


  @ManyToMany(fetch = FetchType.LAZY, cascade = {
      CascadeType.PERSIST,
      CascadeType.MERGE
  })
  @JoinTable(name = "product_categories",
        joinColumns = @JoinColumn(name = "product_id"),
        inverseJoinColumns = @JoinColumn(name = "category_id"))
  private List<Category> categoryList;

}

Useful information - https://vladmihalcea.com/the-best-way-to-use-the-m...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question