Spring Hateoas links and JPA persistence
Asked Answered
N

1

2

I have a JPA entity that i am building hateoas links for:

@Entity
public class PolicyEvent extends ResourceSupport` 

I want the hateoas links generated to be persisted in the PolicyEvent table. JPA doesn't seem to be creating columns in the PolicyEvent table for the _links member in the resourcesupport.

Is there some way to persist the links member via JPA or is my approach itself incorrect (the Hateoas link data should not be persisted).

Thank you

Nessa answered 15/9, 2017 at 18:56 Comment(0)
X
3

I'd advise not to mix JPA entities and HATEOAS Exposed Resources. Below is my typical setup:

The data object:

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

The repository:

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

The HATEOAS resource:

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

The service implementation (interface not shown):

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

Finally, the controller that exposes 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 annotation allows you to add logic in your controller to expose different resource objects.

Xiomaraxiong answered 16/9, 2017 at 3:51 Comment(2)
In my case i have a requirement to save the hateoas links, so they can be queried again in the future from the db. I do want to save these into the db. Is it a bad idea to save the links to the db? JPA seems to ignore any elements in the resourcesupport class that my entity extends.Nessa
The advantage of HATEOAS is to dynamically generate URLs as to not hardcode them in your client - unsure if you are doing the right thing.Xiomaraxiong

© 2022 - 2024 — McMap. All rights reserved.