微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在制作产品类别的对象时如何引用当前对象

如何解决在制作产品类别的对象时如何引用当前对象

我有一个Product类,其中包含一个ProductCategory参考,即 ProductCategory类别和另一个包含产品列表的类ProductCategory。 我正在明智地保存产品类别,因此需要在相应产品中插入当前类别对象。 我想通过主要方法将数据保存在数据库

productCategoryRepository.save(new ProductCategory(1,"Book",Arrays.asList(
   new Product(1,this,"pqr","abc","xyz",true,100,999,LocalDate.Now())
));

实体

Product.java

package com.ecommerce.springbootecommerce.entity;

import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import lombok.Data;

@Entity
@Table(name = "product")
@Data
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "category_id",nullable = false)
    private ProductCategory category;

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

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

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

    @Column(name = "unit_price")
    private BigDecimal unitPrice;

    @Column(name = "image_url")
    private String imageUrl;

    @Column(name = "active")
    private boolean active;

    @Column(name = "units_in_stock")
    private int unitsInStock;

    @Column(name = "date_created")
    @CreationTimestamp
    private Date dateCreated;

    @Override
    public String toString() {
    return "Product [id=" + id + ",category=" + category + ",sku=" + sku + ",name=" + name + ",description=" + description + ",unitPrice=" + unitPrice + ",imageUrl=" + imageUrl + ",active=" + 
    active + ",unitsInStock=" + unitsInStock + ",dateCreated=" + dateCreated + ",lastUpdated=" + 
    lastUpdated + "]";
    }

    @Column(name = "last_updated")
    @UpdateTimestamp
    private Date lastUpdated;

}

ProductCategory.java

package com.ecommerce.springbootecommerce.entity;

import java.util.Set;
import javax.persistence.*;
import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = "product_category")
// @Data --kNown bug
@Getter
@Setter
public class ProductCategory {

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

    @Column(name = "category_name")
    private String categoryName;

    @OnetoMany(cascade = CascadeType.ALL,mappedBy = "category")
    private Set<Product> products;

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。