代码之家  ›  专栏  ›  技术社区  ›  rvs

Spring Hateoas链接和JPA持久性

  •  2
  • rvs  · 技术社区  · 8 年前

    @Entity
    public class PolicyEvent extends ResourceSupport` 
    

    PolicyEvent table . PolicyEvent表

    1 回复  |  直到 8 年前
        1
  •  2
  •   JC Carrillo    8 年前

    我建议不要混合JPA实体和HATEOAS暴露资源。以下是我的典型设置:

    数据对象:

    @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