Reputation: 4358
I have a very basic system using Spring with HATEOAS, and I found a problem. I have two very basic entities a car, and a person. Getters and setters avoided to make the question more readable.
@Entity
public class Car implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long carId;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="personId")
private Person owner;
private String color;
private String brand;
}
@Entity
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long personId;
private String firstName;
private String lastName;
@OneToMany(mappedBy="owner")
private List<Car> cars;
}
This are my repositories:
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(@Param("name") String name);
}
@RepositoryRestResource(collectionResourceRel = "cars", path = "cars")
public interface CarRepository extends PagingAndSortingRepository<Car, Long> {
List<Person> findByBrand(@Param("brand") String name);
}
I can create and query them, but some reference links are broken. For example, a couple of POSTs successfully creates two related entities:
http://localhost:8080/people
{ "firstName" : "Frodo", "lastName" : "Baggins"}
http://localhost:8080/cars
{ "color":"black","brand":"volvo", "owner":"http://localhost:8080/people/1"}
This are the GET reply on them:
http://localhost:8080/cars/2
{
color: "black2",
brand: "volvo2",
_links: {
self: {
href: "http://localhost:8080/cars/2"
},
owner: {
href: "http://localhost:8080/cars/2/owner"
}
}
}
http://localhost:8080/people/1
{
firstName: "Frodo",
lastName: "Baggins",
_links: {
self: {
href: "http://localhost:8080/people/1"
},
cars: {
href: "http://localhost:8080/people/1/cars"
}
}
}
But I don't know why the owner has this URL on the car:
http://localhost:8080/cars/2/owner
which actually doesn't work.
Any help on that?
Upvotes: 0
Views: 1463
Reputation: 4020
It's there because that's what HATEOAS is all about, representing entity/resource relationships with links.
I'm not sure why it doesn't work. I'd guess it probably doesn't work because the owner isn't eagerly fetched when retrieving a car resource.
You can customize which links are generated by following the steps at https://stackoverflow.com/a/24660635/442773
Upvotes: 1