2017-09-15 43 views
0

我有我建立HATEOAS鏈接,JPA實體:春HATEOAS鏈接和JPA持續

@Entity 
public class PolicyEvent extends ResourceSupport` 

我想產生的HATEOAS的鏈接以便在PolicyEvent table被持久化。 JPA似乎沒有在resources支持中的_links成員的PolicyEvent table中創建列。

是否有某種方法可以通過JPA持久化鏈接成員,或者我的方法本身是否不正確(不應持續存在Hateoas鏈接數據)。

謝謝

回答

1

我建議不要混合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註釋允許你在你的控制器添加邏輯來公開不同的資源對象。

+0

在我的情況下,我有一個要求保存討厭的鏈接,所以他們可以從數據庫中再次被查詢。我確實想將這些保存到數據庫中。 將鏈接保存到數據庫是一個壞主意嗎? JPA似乎忽略了我的實體擴展的resourcesupport類中的任何元素。 – rvs

+0

HATEOAS的優勢在於動態生成URL,不會在客戶端對其進行硬編碼 - 不確定您是否做得正確。 –

+0

這太神奇了。甚至[引用](https://stackoverflow.com/a/47995045/6166627)你 – Sam