1

我无法使用spring-data jpa使用spring-data rest获取正确的url以显示自我href。Spring data-rest错误资源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

感谢

回答

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

+0

感谢您的回复。所以你说没有办法将自己的href网址中的资源堆叠起来? like, 'http:// localhost:8080/RESOURCE/{id}/SUB_RESOURCE' using @RepositoryRestResource?我将不得不定义我自己的定制REST控制器?这似乎很奇怪 – user2254140

+0

不幸的是,你可以在我提供的链接中检查,至少在存储库中没有。如果你会找到办法做到这一点 - 很高兴知道。可以完成的方式是通过定义@RepositoryRestController和您的自定义实现并将其与您的资源相关联。 –

+0

如果您想使用存储库实现,您可以执行'SUB_RESOURCE/{ID}?RESOURCE_ID = {RESOURCE_ID}' –