java - 如何从另一个类对象创建变量
问题描述
我有两个 Java 类,Product 和 ProductReview。ProductReview 除了变量 long id 和 String 之外,还有一个名为 Product 的变量,它应该包含 Product 类中的一个对象。例子:
@Entity
@Table(name="Product Reviews")
public class ProductReview implements java.io.Serializable {
@Id
@Column
private long id;
@Column
private String review;
private (stuck here, how do I type another classes object as a variable?)
Product 类有私有变量 long id、String name 和 List 评论(它也从 ProductReviews 类中获取评论)。产品类与 ProductReviews 具有一对多关联,反之亦然。
所以我的问题是:在上面的示例中创建第三个变量的正确语法是什么?该变量应该是 Product 对象的一个实例。
解决方案
您可以使用以下类和映射
@Entity
public class Product {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="Product_Id")
private int id;
@Column(name="Product_Name")
private String name;
@Column(name="Product_Price")
private double price;
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,orphanRemoval=true,mappedBy="product")
private Set<ProductReview> review = new HashSet<ProductReview>();
public Product(String name, double price) {
this.name = name;
this.price = price;
}
//Getter and Setter
}
和 ProductReview 类
@Entity
public class ProductReview {
@javax.persistence.Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="Review_Id")
private int Id;
@Column(name="Review")
private String review;
@ManyToOne()
@JoinColumn(name="Product_Id")
private Product product;
public ProductReview(String review, Product product) {
this.review = review;
this.product = product;
}
public ProductReview() {
}
//Getter and Setter
}