Home > database >  Spring boot - set one entity to list in another entity. ManyToMany relationship
Spring boot - set one entity to list in another entity. ManyToMany relationship

Time:08-10

I have two entities Product and Tag. The relationship between them is ManyToMany, so one product can have multiple tags and one tag can be assigned to multiple products. The way the application works is that Product and Tag are created first and then assigned through PutMapping.

So my question is how can I assign Product to the List of Products in Tag Entity?

Entities:

public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String productName;
    @ManyToMany
    private List<Tag> tag;
}

public class Tag{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String tagName;
    @ManyToMany
    private List<Product> product;
}

And methods that assign Product to the List in Tag and updates it, but this doesnt work. First Im trying to find the existing Tag and Product and then set the product to the List in Tag entity.

public Tag update(Long productID, Long tagID, Tag tag){

 Tag udpatedTag = tagRepository.findById(tagID).get();
 Product product = productRepository.findById(productID).get();

 updatedTag.setProduct((List <Product>) product);
 tagRepository.save(updatedTag)

 return updatedTag;
}

CodePudding user response:

You want to ADD the product to the list, not cast the Product to a List. Also, consider renaming your product variable in Tag to products because it is a Collection of Product. Also, you should consider using a Set for your ManyToMany mappings. Dig around on the interwebs to understand the differences of List vs Set for OneToMany and ManyToMany mappings.

public Tag update(Long productID, Long tagID, Tag tag){

  Tag udpatedTag = tagRepository.findById(tagID).get();
  Product product = productRepository.findById(productID).get();

  // Get the Collection and add the product to it
  updatedTag.getProduct().add(product);
  tagRepository.save(updatedTag)

  return updatedTag;
}

CodePudding user response:

If you want to use many to many structures, you need to create a separate table.

For example ; enter image description here

You can check this site -> https://www.bezkoder.com/jpa-many-to-many/

  • Related