我建议不要混合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