spring - Spring Boot JPA加载多对多

标签 spring hibernate kotlin spring-data hibernate-mapping

我有这两个表:

Student 
- id
- name
- List<Course>

Course
- id
- title
- List<Student>

我有一个StudentRepositoryCourseRepository(JpaRepository)。

当我用以下代码加载学生时:
    fun getAll(): List<Student> {
        return studentRepository.findAll()
    }

我得到一个无限的 list 。

但我希望这个JSON输出:
[
 {
  "id":1,
  "name":"Ben"
  "course": [
   {
   "id":1,
   "title":"Math"
   },
   {
    "id":2,
    "title":"English"
   }
  ]
 }
]

我如何得到这个结果?

//编辑:
我得到一个无限的 list
enter image description here

最佳答案

如果使用 jackson ,则可以通过使用@JsonBackReference(在子级之上)和@JsonManagedReference(在父级之上)注释仅在子级中生成父级的json。

如果要禁止打印该关系,则可以在不需序列化的字段上使用@JsonIgnore@JsonIgnoreProperties批注。

这是Course类的示例:

@JsonIgnoreProperties(value = { "students" })
class Course(...)

您可以找到更多示例here

关于spring - Spring Boot JPA加载多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59933650/

相关文章:

Java Hibernate 验证返回无效字段

android - viewModelScope 未取消

spring - 将 Spring 依赖项注入(inject) JPA EntityListener

java - SQL 错误 : 933, SQLState: 42000 和 ORA-00933: SQL 命令未正确结束

java - 如何使用外部文件夹和 Jars 创建 Jar 文件

java - 使用 jackson 将双向 JPA 实体序列化为 JSON

android - 我正在尝试使用安全参数,但是当我将依赖项添加到项目级别 build.gradle 时,它​​给了我这个错误

java - Kotlin+spring+mustache @Controller 不工作(Whitelabel 错误页面)但 @RestController 工作

java - 在 RabbitMQ 中组接收消息,最好使用 Spring AMQP?

java - 如何更改对象在 spring-data/hibernate/rest 中返回的方式