我用Spring Boot开发了示例应用程序。我有一个抽象类(Employee
)和两个具体的子类,例如全职和兼职员工。
我更喜欢连接类型的继承和JPA提供者创建的3个表。
我还为Employee
创建了REST存储库。如下所示:
package com.caysever.repository;
import com.caysever.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
/**
* Created by alican on 04.05.2017.
*/
@RepositoryRestResource(path = "employee")
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
当我在浏览器中调用**/employee**
URL时,我得到的内容如下:
{
"fullTimeEmployees" : [ {
"name" : "Alican",
"surname" : "Akkuş",
"birthDay" : "2017-05-04T12:37:20.189+0000",
"gender" : "MALE",
"totalWorkingHoursOfWeek" : 40,
"_links" : {
"self" : {
"href" : "http://localhost:8080/fullTimeEmployee/1"
},
"fullTimeEmployee" : {
"href" : "http://localhost:8080/fullTimeEmployee/1"
}
}
}
当我为第一个员工localhost:8080/fullTimeEmployee/1
调用此URL时,我收到404状态代码,未找到。但我将获得第一个使用此URL localhost:8080/employee/1
的员工。
你可以在GitHub看到所有代码 - > https://github.com/AlicanAkkus/jpa-inheritance-strategy
为什么Spring REST会生成fullTimeEmployee
URL?
我认为使用@RepositoryRestResource修改导出详细信息,例如使用/ employee而不是默认值/ full Time Employee
试试吧
@RepositoryRestResource(collectionResourceRel = "fullTimeEmployees", path = "fullTimeEmployees")
或者如果你想使用/ employee
@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
路径设置要在其下导出此资源的段,collectionResourceRel设置在生成到集合资源的链接时要使用的值。
希望这可以帮助
解决方法是为具体类添加存储库接口,共享超类存储库的路径。
@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface FullTimeEmployeeRepository extends JpaRepository<FullTimeEmployee, Long> {
}
@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface PartTimeEmployeeRepository extends JpaRepository<PartTimeEmployee, Long> {
}
无论子类类型如何,这都将生成与“employee”路径的链接。
"_links" : {
"self" : {
"href" : "http://localhost:8080/employee/1"
},
"fullTimeEmployee" : {
"href" : "http://localhost:8080/employee/1"
}
}
我不知道是否有其他方法可以解决这个问题。