Home > Net >  How does Spring create links in JSON?
How does Spring create links in JSON?

Time:01-05

I wrote little bit of code and then Spring showed me this:

{

  "_links" : {
    "employees" : {
      "href" : "http://localhost:8080/api/employees"
    },
    "profile" : {
      "href" : "http://localhost:8080/api/profile"
    }
  }
}

I didnt get how Spring define links like "employees" and "profile" (there is also profile/employees exist) cause I didnt write it anywhere. I only set spring.data.rest.base-path=/api in application.properties file.

Here my code. I made only these changes. Dependencies are:

Rest Repositories

Thymeleaf

JPA

H2

DatabaseLoader.java:

@Component
public class DatabaseLoader implements CommandLineRunner{
    private final EmployeeRepository repository;

    @Autowired 
    public DatabaseLoader(EmployeeRepository repository) {
        this.repository = repository;
    }

    @Override
    public void run(String... strings) throws Exception {
        this.repository.save(new Employee("Frodo", "Baggins", "ring bearer"));
    }
}

"EmployeeRepository.java":

    public interface EmployeeRepository extends CrudRepository<Employee, Long> { 

}

"Employee.java":

    @Entity
public class Employee {

    private @Id @GeneratedValue Long id;
    private String firstName;
    private String lastName;
    private String description;

    private Employee() {}
// and then getters, setters, equals, hashcode, toString... }

CodePudding user response:

The "_links" and "profile" are from HATEOS

It's the "Spring Data Rest" library. See https://docs.spring.io/spring-hateoas/docs/current/reference/html

  •  Tags:  
  • Related