Spring Hateoas链接和JPA持久性 [英] Spring Hateoas links and JPA persistence

查看:160
本文介绍了Spring Hateoas链接和JPA持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JPA实体,正在为其建立仇恨链接:

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

@Entity
public class PolicyEvent extends ResourceSupport` 

我希望生成的Hateoas链接保留在PolicyEvent table中. JPA似乎没有在PolicyEvent table中为resourcesupport中的_links成员创建列.

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.

是否有某种方法可以通过JPA保留链接成员,或者我的方法本身不正确(不应保留Hateoas链接数据).

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).

谢谢

推荐答案

我建议不要混合使用JPA实体和HATEOAS公开资源.下面是我的典型设置:

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

数据对象:

@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资源:

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

@ExposesResourceFor批注允许您在控制器中添加逻辑以公开不同的资源对象.

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

这篇关于Spring Hateoas链接和JPA持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆