我可以获得与@OneToMany相关的对象列表吗



我有两个类:Device和Category。一个设备可以分配一个类别,但一个类别可以分配许多不同的设备。

@Entity
@Data
@Table(name = "devices")
public class Device implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
@Column(name="amount_of_items")
private Integer amountOfItems;
private BigDecimal price;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "category_id")
private Category category;
public Device(String name, String description, Integer amountOfItems, BigDecimal price, Category category){
this.name = name;
this.description = description;
this.amountOfItems = amountOfItems;
this.price = price;
this.category = category;
}
public Device() {}
}

@Entity
@Data
@Table(name = "categories")
public class Category implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
@OneToMany(mappedBy = "category", fetch = FetchType.EAGER)
private List<Device> devices = new ArrayList<>();
public Category(String name, String description){
this.name = name;
this.description = description;
}
public Category() { }
}

我能得到一个类别的实际设备列表吗?以下代码向我返回设备的空列表:

Category category = new Category("Urzadzenia AGD", "tylko dla klientow premium");
categoryRepository.save(category);
Device device = new Device("pralka", "samoobslugowa", 50, new BigDecimal("220"), 
category);
deviceRepository.save(device);
System.out.println(category.getDevies()) ---> returns NULL

我可以像上面那样调用getter吗?

保存方法在数据库中保存后已经返回值,您可以使用此

Category category = new Category("Urzadzenia AGD", "tylko dla klientow premium");
category= categoryRepository.save(category);

Device device = new Device("pralka", "samoobslugowa", 50, new BigDecimal("220"), 
category);
deviceRepository.save(device);

System.out.println(category.getDevies())

并且您必须是类中的makesetter和getter方法在这之后,你有问题堆叠流激发成为使用所有被称为类别和类别的设备
你可以使用@JsonIgnore注释

像这样:

@OneToMany(mappedBy = "category", fetch = FetchType.EAGER)
@JsonIgnore
private List<Device> devices = new ArrayList<>();

最新更新