我正在使用 Spring Boot、JPA、Hibernate 和 Maven 作为存储库管理器来开发 Rest API。在我的模型中,我有类 Club
:
@Entity
@Table( name = "CLUB")
public class Club {
/**
* Id da entidade
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/**
* Atual técnico do clube.
*/
@OneToOne(mappedBy = "actualClub")
private Coach coach;
//Outros atributos, getters e setters
}
上面的类与Coach
类具有@OneToOne
关系:
@Entity
@Table(name = "COACH")
public class Coach extends Person {
/**
* Clube atual do técnico.
*/
@OneToOne
@JoinColumn(name = "CLUB_ID")
private Club actualClub;
//Outros atributos, getters e setters
}
Person
类还有一个带有 @Id
和 @GenerateValue
注释的属性 id。
最后,我还有 Controller 类 ClubController
,它处理一些请求,如下所示:
@RestController
public class ClubController {
/**
* Instância da classe de serviços da entidade <i>Club</i>
*/
@Autowired
private ClubService clubService;
/**
* Retorna JSON que representa o clube com o 'id' especificado.
*
* @param id Identificador do clube a ser buscado.
* @return ResponseEntity Objeto com detalhes da requisição HTTP, como o Status.
*/
@RequestMapping(value = "/clubs/{id}", produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public ResponseEntity<?> getClubById(@PathVariable Long id) {
final Club club = this.clubService.findById(id);
if (club != null) {
return new ResponseEntity<>(club, HttpStatus.FOUND);
} else {
return new ResponseEntity<>("Não encontrado", HttpStatus.NOT_FOUND);
}
}
/*Entre outros métodos...*/
}
问题是:在 /clubs/{id}
中的 GET
中,返回的 JSON 内部有一个循环(无限)依赖项。俱乐部有一个教练,教练也有一个俱乐部,所以……X(
这也会发生在 @OneToMany 关系
Club和
Player`...
我找到了这个解决方案:Link 。我只需在类声明中使用 @JsonIdentityInfo
注释即可。此解决方案的问题是我不会使用的信息的开销(只需考虑 @OneToMany
与 Player
的关系)。此外,正如您在上面的链接中看到的:
"However, JSON id references need to be unique across the entire graph, whereas JPA id’s only need to be unique within the same entity.""
因此,我必须对 JPA id 字段使用 UUID。
我还找到了另一个可能的解决方案:Spring HATEOAS 。在这种情况下,我可以添加指向某些属性的链接 (href),并且只需“按需” 提交申请即可。但似乎 Spring HATEOAS 有一些限制,比如支持嵌入资源......
那么,我应该遵循哪种方法?还有其他解决方案吗?
很快,我打算在 iOS 应用程序中使用这个 API(我不知道它是否有区别)。
抱歉我的英语不好...来自巴西的问候 x)
最佳答案
使用 @JsonIgnoreProperties
注释这两种关系
如下
// Employee entity, owning side of relationship
@ManyToOne(cascade = CascadeType.ALL)
@JsonIgnoreProperties("employee")
private Department department;
// Department side, inverse side of relationship
@OneToMany(mappedBy = "department")
@JsonIgnoreProperties("department")
private Collection<Employee> employee;
关于java - 使用 Spring Boot 的 RESTful API 中的循环依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44169390/