Springboot如何查询多对多关系

时间:2018-12-15 07:18:04

标签: java jpa spring-data-jpa many-to-many entity

我有两个实体,可以将它们称为“类别”和“产品”。这两个实体通过多对多关系进行映射。

  

我的问题是我正在尝试从产品中获取类别信息。尝试此操作将导致空类别。

这是我的代码:

PersistenceEntity

@MappedSuperclass
public class PersistenceEntity implements Serializable {
    private static final long serialVersionUID = 4056818895685613967L;
    // Instance Variables
    @Id
    @Column(unique = true)
    @GeneratedValue(strategy = GenerationType.TABLE)
    protected Long id;
    @JsonIgnore
    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    protected Date creationDate = new Date();

    ...Getters and Setters omitted for brevity

}

类别

@Entity
@Table(name = "category")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Category extends PersistenceEntity{

    private static final long serialVersionUID = 1L;

    @Column(nullable = false)
    private String categoryName;

    @Column(nullable = false)
    private Boolean active;

    @Column(nullable = true)
    private String picture;

    @JsonIgnore
    private MetaData metadata;

    @ManyToMany(fetch = FetchType.EAGER,mappedBy = "categories")
    private Set<Product> products;

        ...Getters and Setters omitted for brevity

 }

产品

@Entity
@Table(name = "products",uniqueConstraints = { @UniqueConstraint(columnNames = "productCode")})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Product extends PersistenceEntity {

    private static final long serialVersionUID = 8727166810127029053L;

    @Column(name = "product_name")
    private String name;

    private String productImageUrl;

    @JsonIgnore
    @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @JoinTable(name="category_products", 
        joinColumns={@JoinColumn(name="product_id", unique = false)}, 
        inverseJoinColumns={@JoinColumn(name="category_id", unique = false)})
    private Set<Category> categories;


            ...Getters and Setters omitted for brevity

  }

ProductServiceImplementation

@Service
public class ProductService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ProductRepository productRepository;

    public List<Product> getProductsByShopId( Long id) {
      List<Product> productList = new ArrayList<>();
      productList = productRepository.findByShopId(id);
      return productList;
    }

    public Set<Long> getCategoryIds(List<Product> products){

        Set<Long> categoriesIDs = new HashSet<Long>();


        for (Product product : products) {
            product.getCategories().forEach(category -> {
                categoriesIDs.add(category.getId());
            });
        }

        return categoriesIDs;
    }

}

问题在于获取映射到产品列表的categoryId。

  

如何从产品中获取CategoryId。我的getCategoryIds函数总是返回空

 public Set<Long> getCategoryIds(List<Product> products){

    Set<Long> categoriesIDs = new HashSet<Long>();


    for (Product product : products) {
        product.getCategories().forEach(category -> {
            categoriesIDs.add(category.getId());
        });
    }

    return categoriesIDs;
}

0 个答案:

没有答案