问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/46245938/spring-hateoas-links-and-jpa-persistence