我們目前在我們最新的項目中實現了一個API庫。 我們試圖使用Spring HATEOAS和HAL作爲合適的庫來生成json hal響應。在HATEOAS中命名Spring頁面密鑰_embedded PagedResource
使用Spring引導1.2.5.RELEASE +提供的Spring HATEOAS版本。 目前我們正在映射實際的JPA實體作爲資源返回。
I.e.我們的實體看起來是這樣的:
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "users")
public class User {
@Id
private UUID id;
@Column(nullable = false, length = 70)
private String firstName;
@Column(nullable = false, length = 70)
private String lastName;
}
我們的倉庫:
public interface UserRepository extends PagingAndSortingRepository<User, UUID>, JpaSpecificationExecutor<User> {
User findByUsername(String username);
}
我們的服務:
@Service
@Transactional
public class UserService implements UserDetailsService {
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Transactional
public Page<User> findAll(Pageable pageable) {
return this.userRepository.findAll(pageable);
}
}
的RestController:
@RestController
@RequestMapping(value = "/users", produces =MediaType.APPLICATION_JSON_VALUE) // this is done otherwise objectmapper returns xml for some reason
public UserRestController {
public UserService userService;
public EntityLinks entityLinks;
@Autowired
public UserRestController(UserService userService, EntityLinks entityLinks) {
this.userService = userService;
this.entityLinks = entityLinks;
}
@RequestMapping(method = RequestMethod.GET)
public PagedResource<Resource<User>> getUsers(Pageable pageable, PagedResourcesAssembler<User> pagedResourcesAssembler) {
Page<User> userPage = this.userService.findAll(pageable);
PagedResources<Resource<User>> userPagedResources =
pagedResourcesAssembler.toResource(
usersPage,
linkTo(methodOn(UserRestController.class).showUsers(pageable, pagedResourcesAssembler)).withSelfRel());
return userPagedResources;
}
}
可以說,我設置的默認頁面大小爲1的頁面變得越來越普遍適當的。將鏈接設置爲上一頁/下一頁。 '可嵌入'屬性正在生成,但是然後我們得到「userList」:第{{用戶}]頁面1和頁面2得到我們'user $$ _ jvst163_9List「:[{user}]。
有沒有一種方法來實際命名頁面列表屬性(我一直在試圖找到網絡上的東西,但無濟於事)。
例如:
{
"_links": {
"self": {
"href": "http://localhost:8080/users{?page,size,sort}",
"templated": true
},
"next": {
"href": "http://localhost:8080/users?page=1&size=1&sort=firstname,lastname,asc"
}
},
"_embedded": {
"userList": [{
"id": "2027bea9-cfdc-4724-b29c-39b3f64cbfd5",
"firstname": "admin",
"lastname": "asdf",
}]
},
"page": {
"size": 1,
"totalElements": 2,
"totalPages": 2,
"number": 0
}
}
{
"_links": {
"self": {
"href": "http://localhost:8080/users{?page,size,sort}",
"templated": true
},
"prev": {
"href": "http://localhost:8080/users?page=0&size=1&sort=firstname,lastname,asc"
}
},
"_embedded": {
"user_$$_jvst163_9List": [{
"id": "52c0c09e-c386-4aec-9723-f8beaf99adc5",
"username": "admin",,
"firstname": "firstname",
"lastname": "lastname"
}]
},
"page": {
"size": 1,
"totalElements": 2,
"totalPages": 2,
"number": 1
}
}
通過使用Spring HATEOAS包中的@Relation解決了這個問題。即@Relation(collectionRelation =「users」) – Konstantin
隨時回答你自己的問題,並提供詳細信息,使其對他人有用! – Raman