我有兩個JPA實體,一個帶有SDR導出的存儲庫,另一個帶有Spring MVC控制器和一個非導出的存儲庫。混合彈簧MVC +彈簧數據休息導致奇怪的MVC響應
MVC公開實體具有對SDR被管實體的引用。請參閱下面的代碼參考。
從UserController
檢索User
時,問題就會發揮作用。 SDR管理實體不會序列化,並且似乎Spring可能試圖在響應中使用HATEOAS參考。
這裏是一個完全填充User
一個GET
樣子:
{
"username": "[email protected]",
"enabled": true,
"roles": [
{
"role": "ROLE_USER",
"content": [],
"links": [] // why the content and links?
}
// no places?
]
}
如何,我不是從我的控制器與嵌入式SDR返回User
實體管理實體?
Spring MVC的託管
實體
@Entity
@Table(name = "users")
public class User implements Serializable {
// UID
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private Long id;
@Column(unique = true)
@NotNull
private String username;
@Column(name = "password_hash")
@JsonIgnore
@NotNull
private String passwordHash;
@NotNull
private Boolean enabled;
// No Repository
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@NotEmpty
private Set<UserRole> roles = new HashSet<>();
// The SDR Managed Entity
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "user_place",
joinColumns = { @JoinColumn(name = "users_id") },
inverseJoinColumns = { @JoinColumn(name = "place_id")})
private Set<Place> places = new HashSet<>();
// getters and setters
}
回購
@RepositoryRestResource(exported = false)
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
// Query Methods
}
控制器
@RestController
public class UserController {
// backed by UserRepository
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping(path = "https://stackoverflow.com/users/{username}", method = RequestMethod.GET)
public User getUser(@PathVariable String username) {
return userService.getByUsername(username);
}
@RequestMapping(path = "/users", method = RequestMethod.POST)
public User createUser(@Valid @RequestBody UserCreateView user) {
return userService.create(user);
}
// Other MVC Methods
}
SDR管理
實體
@Entity
public class Place implements Serializable {
// UID
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotBlank
private String name;
@Column(unique = true)
private String handle;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "address_id")
private Address address;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "contact_info_id")
private ContactInfo contactInfo;
// getters and setters
}
回購
public interface PlaceRepository extends PagingAndSortingRepository<Place, Long> {
// Query Methods
}
我假設你有PlaceRepository的@Repository註釋 - 只是沒有發佈在這裏?你可以添加例外的文字嗎? – lenach87
@ lenach87 - 除非需要進一步配置它,否則SDR不需要「@ Repository」註釋。也沒有例外,只是沒有序列化。 – bvulaj
也許你的JPA實現存在問題?如果你使用的是Hibernate,它可以使得只有一個包的急切加載。你可以創建一個自定義查詢來迫使它加載,或者只是在將它作爲響應發送之前調用屬性的訪問者(這將強制hibernate加載屬性包)。 –