我建議不要混合JPA實體和HATEOAS Exposed Resources。下面是我的典型設置:
數據對象:
@Entity
public class MyEntity {
// entity may have data that
// I may not want to expose
}
存儲庫:
public interface MyEntityRepository extends CrudRepository<MyEntity, Long> {
// with my finders...
}
的HATEOAS資源:
public class MyResource {
// match methods from entity
// you want to expose
}
服務實現(未顯示接口) :
@Service
public class MyServiceImpl implements MyService {
@Autowired
private Mapper mapper; // use it to map entities to resources
// i.e. mapper = new org.dozer.DozerBeanMapper();
@Autowired
private MyEntityRepository repository;
@Override
public MyResource getMyResource(Long id) {
MyEntity entity = repository.findOne(id);
return mapper.map(entity, MyResource.class);
}
}
最後,暴露出資源控制器:
@Controller
@RequestMapping("/myresource")
@ExposesResourceFor(MyResource.class)
public class MyResourceController {
@Autowired
private MyResourceService service;
@Autowired
private EntityLinks entityLinks;
@GetMapping(value = "/{id}")
public HttpEntity<Resource<MyResource>> getMyResource(@PathVariable("id") Long id) {
MyResource myResource = service.getMyResource(id);
Resource<MyResource> resource = new Resource<>(MyResource.class);
Link link = entityLinks.linkToSingleResource(MyResource.class, profileId);
resource.add(link);
return new ResponseEntity<>(resource, HttpStatus.OK);
}
}
的@ExposesResourceFor
註釋允許你在你的控制器添加邏輯來公開不同的資源對象。
在我的情況下,我有一個要求保存討厭的鏈接,所以他們可以從數據庫中再次被查詢。我確實想將這些保存到數據庫中。 將鏈接保存到數據庫是一個壞主意嗎? JPA似乎忽略了我的實體擴展的resourcesupport類中的任何元素。 – rvs
HATEOAS的優勢在於動態生成URL,不會在客戶端對其進行硬編碼 - 不確定您是否做得正確。 –
這太神奇了。甚至[引用](https://stackoverflow.com/a/47995045/6166627)你 – Sam