Spring 1.3.5
我尽我所能来验证这一点;通过Postman传入的JSON与我在测试中生成的JSON相同。通过Postman更新实体工作正常。通过mockMvc
进行更新失败。首先,它失败了400,我收到了以下错误:
Could not read document: Already had POJO for id (java.lang.Long) [[ObjectId: key=1, type=com.fasterxml.jackson.databind.deser.impl.PropertyBasedObjectIdGenerator, scope=java.lang.Object]] (through reference chain: com.foo.Department["id"])
在做了一些研究之后,我最终将scope=Department.class
添加到了部门的@JsonIdentityInfo
。这解决了这个问题(虽然我真的不明白为什么),现在它失败了,因为它声称@OneToOne
关系属性为null,即使我通过调试器查看实体是正确的。
这是我的Department
实体:
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id", scope = Department.class)
@JsonRootName(plural = "departments", singular = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(min = 5, max = 150)
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "brand_id")
@JsonBackReference("brand-departments")
private Brand brand;
@OneToOne(fetch = FetchType.LAZY)
@NotNull
@JoinColumn(name = "department_group_id")
private DepartmentGroup departmentGroup;
@NotNull
@Size(max = 10)
private String shortDescription;
// getters and setters
}
同样,通过bootRun
并从Postman发布JSON,一切正常。它只在运行我的测试时中断。这是我的测试:
@Test
public void successfulUpdateDepartment() throws Exception {
Department existingDepartment = departmentService.first();
UpdateDepartment department = new UpdateDepartment(existingDepartment.getId(), "Chngd Dep Y", existingDepartment.getShortDescription(), new DepartmentGroupId(departmentGroup.getId()));
mockMvc.perform(put(URL)
.contentType(contentType)
.content(this.json(department)))
.andExpect(status().isOk());
}
答案 0 :(得分:0)
我已经确定了为什么这在应用程序运行时有效但不用于测试。如果ID重叠,则使用scope
的{{1}}属性。运行应用程序时,Department和DepartmentGroup对@JsonIdentityInfo
有不同的值,但在我的测试中,它们都是1.向两个实体添加id
解决了问题。