【发布时间】:2023-01-25 04:34:32
【问题描述】:
我有一个实体 TechnicalStack 和一个实体类别,其中一个类别内部可能有很多 TechnicalStack。
这是我的代码:
@Entity
@Table(name = "technical_stack")
public class TechnicalStack implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long ID;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
private String Question;
@Column(columnDefinition = "NVARCHAR(MAX)")
private String Answer;
private int Bookmark;
private int CheatSheet;
}
和类别
@Entity
@Table(name="categories")
public class Category implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "category", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@Fetch(FetchMode.SUBSELECT)
private Set<TechnicalStack> techList = new HashSet<>();
private String categoryName;
private String description;
}
我只使用普通的 JPA 函数、findAll、save 等。
因此,当我保存类别项目时,例如:
{
"description" : "...",
"categoryName" : "name1update",
"techList": [{
"question" : "ABC",
"answer" : "XYZ"
}]
}
当我已经在 2 表 TechStack 和类别中有一些记录时,我想查看类别,我通过调用 findAll()
`[
{
"id": 1,
"techList": [],
"categoryName": "name1update",
"description": "..."
}
]`
但是,当我检查技术堆栈记录时,我是这样的:
`{
"category": {
"id": 1,
"techList": [],
"categoryName": null,
"description": null
},
"id": 3,
"question": "question11",
"answer": "answer22",
"bookmark": 0,
"cheatSheet": 0
}`
控制器:
@PostMapping("/category/viewAll")
public List<Category> viewAllCategory() {
return repo.findAll();
}
技术堆栈工作正常,但反之亦然。类别中的 techyList 不应为空。 我如何实现,所以当jpa通过findAll()调用类别时,我也得到了techList?
我想我可以通过手动调用 techList 来完成。那不是问题。一条查询语句调用类别id,一条查询语句调用刚刚调用的列表中的技术堆栈。但我不认为这是完全使用的 JPA/Hibernate。
谢谢
【问题讨论】:
-
您正在为您的 techList 列表使用 Lazy Fetch。所以它不会与父实体一起出现。您宁愿需要使用 Eager Fetch 或进行单独的查询并填充对象帖子。
-
我试过了。但它仍然是一样的。此外,我正在使用 RestController,例如:@PostMapping("/category/viewAll") public List<Category> viewAllCategory() { return repo.findAll(); JSON 解析将使它运行
-
你能分享你的完整代码吗?很难找到可用信息的问题。
-
这几乎就是一切。我只有 2 个实体和 1 个运行 categoryRepository.findAll 的控制器
-
我在这里没有看到控制器
标签: java spring jpa spring-data-jpa