Home > Software engineering >  How do you create a JPA Repository for a table with many to many mapping
How do you create a JPA Repository for a table with many to many mapping

Time:10-15

I have created the following java classes

Product.java

@Entity
public class Product {

    @Id
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    @GeneratedValue(generator = "UUID")
    private UUID id;
    private String name;

    @Lob
    private String description;
    private String category;
    private String itemCode;

    @OneToMany(mappedBy = "product")
    private List<ProductFeatures> productFeatures;

    @ManyToMany
    @JoinTable(
            name = "product_tags",
            joinColumns = @JoinColumn(name = "product_id"),
            inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    private List<Tag> productTags;

    private int quantity;
    private Timestamp dateModified;

    @ManyToOne
    @JoinColumn(name = "vendor_id")
    private Vendor vendor;

}

and

Tag.java

@Entity
public class Tag {

    @Id
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    @GeneratedValue(generator = "UUID")
    private UUID id;
    private String name;

    @Lob
    private String description;

    @ManyToMany(mappedBy = "productTags")
    private List<Product> products;

}

These two classes will create three tables products, tags and product_tags. Now, I wanted to create a repository for the product_tags table. How do I go about it?

Any suggestions would be highly appreciated.

CodePudding user response:

You can't. A JpaRepository requires an entity and there is no ProductTag entity. product_tag is just a join table that is used to satisfy the ManyToMany relationship between Product and Tag. The JpaRepostories that you require are Product and Tag

@Repository
public interface ProductRepository extends JpaRepository<Product, UUID> {
}

@Repository
public interface TagRepository extends JpaRepository<Tag, UUID> {
}

  • Related