Course.java
@Entity
@Table
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Course {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotEmpty
private String description;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "subject_course", joinColumns = @JoinColumn(name = "subject_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id"))
private Set<Subject> subjects = new HashSet<Subject>();
---- getter/setter ----
Subject.java
@Entity
@Table
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Subject {
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String description;
@ManyToMany(mappedBy = "subjects", fetch=FetchType.EAGER)
@Cascade({CascadeType.DELETE, CascadeType.SAVE_UPDATE})
private Set<Course> courses = new HashSet<Course>();
---- getter/setter ----
在Spring中请求配置:
@RequestMapping(value = "/courses", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<?> getAllCourses() {
List<Course> courses = courseService.getAllCourses();
if (courses.isEmpty()) {
return new ResponseEntity<Message>(new Message("error", "No course found!"), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<List<Course>>(courses, HttpStatus.OK);
}
Hibernate版本:4.2.0.Final
春季版:3.2.8.RELEASE
杰克逊:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.4</version>
</dependency>
期待O / P
[{
"id": 1,
"description": "BCA",
"subjects":[{
"id":1,
"description":"Physics",
"courses":[1,2,3] //Either show blank array or only ids
}]
},{
"id": 2,
"description": "BSC",
"subjects":[{
"id":1,
"description":"Physics",
"courses":[1,2,3]
}]
},{
"id": 3,
"description": "BA",
"subjects":[{
"id":1,
"description":"Physics",
"courses":[1,2,3]
}]
},]
但是得到O / P:
[
{
"id": 1,
"description": "BCA",
"subjects": [
{
"id": 1,
"description": "Math",
"staffs": [],
"courses": [
{
"id": 4,
"description": "BDA",
"subjects": [
1
],
"students": []
},
{
"id": 3,
"description": "BBA",
"subjects": [
1
],
"students": []
},
1
],
"students": []
}
],
"students": [
{
"id": 1,
"name": "",
"age": 0,
"gender": null,
"course": 1,
"subjects": []
}
]
},
3,
4
]
根据实际的o / p,它会在第二级停止递归。但我的要求是不要重复来自孩子的相同对象数据......这意味着课程不得在Subject的课程属性中重复其数据。同样,如果从主题调用相同,则主题不应重复课程主题属性值。最好跳过,如果不能,则只显示以逗号分隔的id值。
请告知如何解决此问题。
答案 0 :(得分:0)
您可以在Subject类中使用@JsonIgnore
,如下所示:
@ManyToMany(mappedBy = "subjects", fetch=FetchType.EAGER)
@Cascade({CascadeType.DELETE, CascadeType.SAVE_UPDATE})
@JsonIgnore
private Set<Course> courses = new HashSet<Course>();