0

Having a @ReposirotyRestResource bound to an entity AppUser and extending the JpaRepository like this:

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface AppUserRepository extends JpaRepository<AppUser, Long> {

    AppUser findByUsername(@Param("username") String username);

}

Where AppUser looks like this:

@Entity
@Table(name = "app_user")
public class AppUser extends AbstractTimestampEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // ..
}

I want to receive the id whenever I want to appUserRepository.findUserByUsername("whatever") - for some reason the default behavior seems to be to not return this field.


Extra points for either pointing out an error on my side or explain to me why this is the default behavior (and a good idea).

Cepr0
  • 28,144
  • 8
  • 75
  • 101
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
  • Take a look at [this](https://stackoverflow.com/a/49344988/4071001) in case you need to expose the identifiers for all entities, or only for those that extends or implements specific super class or interface, or with some specific annotation. – lcnicolau Jul 07 '18 at 19:00

1 Answers1

2

Your question is about Spring Data REST (you should update tags) - it automatically 'transforms' your repositories to REST controllers with HATEOES where resource ID is the part of included to the resource self link, like: /appUsers/1. So by default resource body does not contain its ID.

If you need to include it you can extend RepositoryRestConfigurerAdapter and add exposing ID of necessary classes, for example like the follow:

@Bean
public RepositoryRestConfigurerAdapter repositoryRestConfigurerAdapter() {
    return new RepositoryRestConfigurerAdapter() {

        @Override
        public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
            config.exposeIdsFor(AppUser.class);
            super.configureRepositoryRestConfiguration(config);
        }
    };
}
Cepr0
  • 28,144
  • 8
  • 75
  • 101
  • Indeed - I found another question on so that faces the same issue. From github issues I can see that this is done in order to make the client kind of ID-agnostic. – Stefan Falk Apr 01 '18 at 19:45