【发布时间】:2018-09-18 22:55:44
【问题描述】:
我在使用 JPA 和 RelationsShips One to Many with Jackson 和 Spring Rest 时遇到问题...我尝试找到多种解决方案,但任何方法都对我有用,但我不知道问题出在哪里。
例如,我有一个具有一对多/多对一关系的表 Team
我有两个存储库,一个用于团队,另一个用于玩家
Team >>> has Many >> Player
Player >>> many to one >> Team
我的实体团队有以下内容
@Entity
@Table(name = "teams")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Team {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long teamId;
private String abbreviation;
private String team;
private String simpleName;
private String logo;
@OneToMany(cascade = {CascadeType.ALL,CascadeType.PERSIST,CascadeType.MERGE}, mappedBy = "team")
@Column(nullable = false)
private List<Player> players;
Theirs getters/setter , hashcodes and string similars.
另一方面是实体玩家
@Entity
@Table(name = "player")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Player {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "teams_id", nullable=true)
private Team team;
private String name;
所以,我在存储库的控制器中有典型的 get 调用。
@RestController
@RequestMapping("/api/public/team")
public class TeamController {
@Autowired
private TeamRepository teamRepository;
@Autowired
private GenericMethods genericMethods;
@GetMapping(value = "/{id}")
public Team getPersona(@PathVariable("id") int id) {
return teamRepository.findOne(genericMethods.toLong(id));
}
和存储库
@Repository
public interface TeamRepository extends JpaRepository<Team, Long> {
}
现在,当我调用此端点时,我收到以下答案,我认为这是不正确的,我只需要一个包含玩家的列表
{
"id":2,
"teamId":0,
"abbreviation":null,
"team":null,
"simpleName":"Betis",
"logo":null,
"players":[
{
"id":1,
"team":2,
"category":{
"id":1,
"nombre":"juvenil a",
"language":null,
"description":null,
"league":[
],
"players":[
1,
{
"id":2,
"team":2,
"category":1,
"name":"hulio"
}
]
},
"name":"pepe"
},
2
]
}
我需要访问玩家和团队的信息,所以我不能使用@JsonIgnoreProperties
有人可以帮忙解决这个问题吗?
【问题讨论】:
-
如果只需要播放器列表,为什么不直接返回列表呢?因为来电者已经认识团队。