1
votes

I'm having trouble getting the correct url to show up for a self href using spring-data rest with spring-data jpa.

So I have a Student class:

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

    @Id
    private Long id;

    ...
    ...

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

with a corresponding repository file

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

}

There is also a StudentInformation class

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

    @Id
    private Long id;

    ...
    ...
}

(other properties / getters / setters omitted)

with a corresponding repository

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

The student displays as I would expect when i search for one by its 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"
    }
  }
} 

except when I follow the link from students to studentInformation, studentInformation has an incorrect self link.

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

How do I get that link to read "href": "http://localhost:8080/students/1/studentinformation instead of "href": "http://localhost:8080/students/studentinformation/1"

Thanks

1

1 Answers

1
votes

First of all, multi-segment path like students/studentinformation just may not work as it is not supported, see this answer, so don't focus on designing your URL's. If you really need to have http://localhost:8080/students/1/studentinformation representation - you need to define a custom controller for that and don't rely on Spring Data REST.

Secondly, wouldn't it be better to use projections to have different student data on /students endpoint? If that's just a different representation of Student resource, I would go with projections, e.g. students/1?projection=minimal and students/1?projection=full.

In case studentinformation contains totally different data than the students and it is not a representation of Student resource, just define an endpoint for /studentinformation.