Home > Net >  Spring Boot entity many-to-many native query
Spring Boot entity many-to-many native query

Time:10-08

I have category class as list in entity. How can I fill this entity with a native query?

Product.java

public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer pid;
    
    private String name;

    @ManyToMany
    @JoinTable(
        name = "product_category ",
        joinColumns = @JoinColumn(
                name = "pro_id", referencedColumnName = "pid"),
        inverseJoinColumns = @JoinColumn(
                name = "cat_id", referencedColumnName = "cid"))
    private List<Category> Categories;
}

Category.java

   public class Category {

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

    private String catname;

    private String desc;

    @ManyToMany(mappedBy = "categories")
    private List<User> users;

}

How should I write a query? How can I fill the Categories list

@Query(value = "*****", nativeQuery = true)
    List<Product> productList();

CodePudding user response:

Could you please elaborate your question. As you can get the collection list if it is mapped just by find all function of Product Repository.

However, if you are looking to insert collection you can use cascade type in Categories field of Product Repository. This will automatically insert the categories entity once you save the Product entity to database by setting categories list in Product entity.

CodePudding user response:

Instead of native query you can use hibernate queries like the below to find something useful.

  1. Find all ProductRepository.findAll();
  2. Hibernate query
@Query(select product from Product product join product.categories categories)
List<Product> getAllProducts();

you can also sort the above queries using Pageable Object.

  • Related