Search code examples
spring-dataspring-data-restspring-restcontroller

Spring Data Rest CrudRepository vs ReadOnlyRepository


I noticed an anomaly in the way Spring Data Rest repositories are behaving. I have two types of entities. in my application - readonly entities (for reference data like statecodes, country codes, zip codes etc.). I don't want to let the end user change these. So I implemented the following ReadOnly repository.

@NoRepositoryBean
public interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {

    T findOne(ID id);

    Iterable<T> findAll();
}


@Repository
public interface StateRepository extends ReadOnlyRepository<State, Long> {
}

Now, all other entities have CrudRepositories associated with them because they are editable entities like addresses which reference the states and zip codes.

Here's an example.

@Repository
public interface CustomerRepository extends CrudRepository<Address, Long> {
}

I have a controller for both readonly and editable entities, with a pass-through call to the repositories.

@RestController
@RequestMapping(value = "/addresses", produces = MediaType.APPLICATION_JSON_VALUE)
public class AddressController {

    @Autowired
    private AddressRepository addressRepository;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public Iterable<Address> getAllAddresses() {
        return addressRepository.findAll();
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public Address getAddress(@PathVariable("id") Long id) {
        return addressRepository.findOne(id);
    }
}

I have an identical Controller corresponding to the State entity.

Funnily enough, the request to StateController gives me a HATEOAS json response, while the request to Address gives me a non HATEOAS json response. What gives?


Solution

  • My bad. My application server did not redeploy certain repositories. This is a non-issue.

    So for those running into these issues, you are likely using hot-code replace feature of your IDE. Consider restarting your app and it should be a non-issue.