Spring Hateoas Relationships and Saving JPA

I have a JPA object that I create links for links to:

@Entity public class PolicyEvent extends ResourceSupport` 

I want hate related links to be stored in the PolicyEvent table . The JPA does not seem to create columns in the PolicyEvent table for the _links member in resourceupport.

Is there a way to preserve link member via JPA or is my approach wrong (Hateoas link data should not be saved).

thanks

+1
source share
1 answer

I would advise against mixing JPA and HATEROAS Exposed Resources objects. Below is my typical setup:

Data Object:

 @Entity public class MyEntity { // entity may have data that // I may not want to expose } 

Repository:

 public interface MyEntityRepository extends CrudRepository<MyEntity, Long> { // with my finders... } 

HATEOAS Resource:

 public class MyResource { // match methods from entity // you want to expose } 

Service implementation (interface not shown):

 @Service public class MyServiceImpl implements MyService { @Autowired private Mapper mapper; // use it to map entities to resources // ie 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); } } 

Finally, the controller that provides the resource:

 @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); } } 

The @ExposesResourceFor allows you to add logic to your controller to expose different resource objects.

+2
source

Source: https://habr.com/ru/post/1274343/


All Articles