【问题标题】:Spring data-rest incorrect resource hrefSpring data-rest不正确的资源href
【发布时间】:2017-03-18 18:05:00
【问题描述】:

我在使用 spring-data rest 和 spring-data jpa 获得正确的 url 以显示 self href 时遇到问题。

所以我有一个学生类:

@Entity
@Table(name="student", schema="main")
public class Student {

    @Id
    private Long id;

    ...
    ...

    @OneToOne
    @JoinColumn(name = "id")
    private StudentInformation studentInformation;
}

带有相应的存储库文件

@RepositoryRestResource(collectionResourceRel = "students", path = "students")
public interface StudentRepository extends PagingAndSortingRepository<Student, Long> {

}

还有一个 StudentInformation 类

@Entity
@Table(name="studentinformation", schema="main")
public class StudentInformation {

    @Id
    private Long id;

    ...
    ...
}

(省略其他属性/getter/setter)

有相应的仓库

@RepositoryRestResource(collectionResourceRel = "studentinformation", path = "students/studentinformation")
public interface StudentInformationRepository extends CrudRepository<StudentInformation, Long> {
}

当我通过 id 搜索学生时,学生的显示与我预期的一样,

{
  "id": 1,
  ...
  ...
  "_links": {
    "self": {
      "href": "http://localhost:8080/students/1"
    },
    "student": {
      "href": "http://localhost:8080/students/1"
    },
    "studentinformation": {
      "href": "http://localhost:8080/students/1/studentinformation"
    }
  }
} 

除了当我点击从学生到 studentInformation 的链接时,studentInformation 的自我链接不正确。

{
  "id": 1,
  ...
  ...
  "_links": {
    "self": {
      "href": "http://localhost:8080/students/studentinformation/1"
    },
    "studentinformation": {
      "href": "http://localhost:8080/students/studentinformation/1"
    }
  }
}

如何让该链接阅读 "href": "http://localhost:8080/students/1/studentinformation 代替 "href": "http://localhost:8080/students/studentinformation/1"

谢谢

【问题讨论】:

    标签: spring spring-data spring-data-jpa spring-data-rest spring-hateoas


    【解决方案1】:

    首先,像students/studentinformation 这样的多段路径可能无法正常工作,因为它不受支持,请参阅this answer,因此不要专注于设计您的 URL。如果你真的需要http://localhost:8080/students/1/studentinformation 表示 - 你需要为此定义一个自定义控制器,不要依赖Spring Data REST

    其次,使用projections/students 端点上拥有不同的学生数据不是更好吗?如果这只是 Student 资源的不同表示,我会选择预测,例如students/1?projection=minimalstudents/1?projection=full

    如果studentinformation 包含与students 完全不同的数据并且它不是Student 资源的表示,只需为/studentinformation 定义一个端点。

    【讨论】:

    • 感谢您的回复。所以你是说没有办法在self href URL中堆叠资源?比如,http://localhost:8080/RESOURCE/{id}/SUB_RESOURCE 使用 @RepositoryRestResource?我必须定义自己的自定义 REST 控制器吗?这似乎很奇怪
    • 不幸的是,您可以在我提供的链接中进行检查,至少不能在存储库中进行检查。如果你能找到任何方法来做到这一点 - 很高兴知道。可以通过使用您的自定义实现定义 @RepositoryRestController 并将其与您的资源相关联来完成它。
    • 如果你想使用存储库实现,你可以做SUB_RESOURCE/{ID}?RESOURCE_ID={RESOURCE_ID}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2020-05-07
    • 2014-11-10
    • 2021-05-12
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    相关资源
    最近更新 更多