从Spring Data REST返回JSON响应中的ID

时间:2017-05-18 11:36:05

标签: spring-boot spring-data-rest

我有一个实体

@Entity
@Table(name = "books")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

我像这样初始化它

@PostConstruct
public void init() {
    List<String> newFiles = this.listFiles();
    newFiles.forEach(filename -> {
        Book book = new Book();
        book.setName(filename);

        dbRepository.save(book);
    });
}

如果我将save的结果设置为Book的实例,我可以获得id而不是null - 所以id是创造了很好的。

我定义了一个存储库

@RepositoryRestResource
public interface IBooksRepository extends CrudRepository<Book, Long> {
}

我想用它来获取数据并将数据设置到数据库中的books表中。

当我尝试使用repository rest访问curl localhost:8080/books时,我收到了此回复

{
   "_embedded":{
      "books":[
         {
            "name":"simple-file.txt",
            "_links":{
               "self":{
                  "href":"http://localhost:8080/books/1"
               },
               "book":{
                  "href":"http://localhost:8080/books/1"
               }
            }
         }
      ]
   },
   "_links":{
      "self":{
         "href":"http://localhost:8080/books"
      },
      "profile":{
         "href":"http://localhost:8080/profile/books"
      }
   }
}

books元素仅返回name。如何让它返回id,与name处于同一级别?

5 个答案:

答案 0 :(得分:11)

Spring Data Rest 默认隐藏 ID,为了让它在JSON中你必须为你的实体手动配置它。根据您的弹簧版本,您可以提供自己的配置(旧):

@Configuration
public class ExposeEntityIdRestConfiguration extends RepositoryRestMvcConfiguration {

    @Override
    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Book.class);
    }
}

...或注册RepositoryRestConfigurer(当前):

@Component
public class ExposeEntityIdRestMvcConfiguration extends RepositoryRestConfigurerAdapter {

  @Override
  public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    config.exposeIdsFor(Book.class);
  }
}

有关详细信息,请参阅Spring Data Rest documentation

答案 1 :(得分:6)

已接受的答案会覆盖已弃用的方法。这是更新的版本:

"xdotool set_desktop $((cur=$(xdotool get_desktop), max=$(xdotool get_num_desktops), (cur + 1) % max))"

另一种方法是在您的 @Component public class RestConfig implements RepositoryRestConfigurer { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) { config.exposeIdsFor(Book.class); } } 注释类中实现 RepositoryRestConfigurer

@SpringBootApplication

答案 2 :(得分:2)

@Component
public class RestConfig implements RepositoryRestConfigurer {

    @Override
      public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Book.class);
        //config.exposeIdsFor(Library.class);
      }

}

答案 3 :(得分:0)

现在有一个静态方法Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/users/customuser/ Django Version: 3.0 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'users.apps.UsersConfig', 'contacts.apps.ContactsConfig', 'API.apps.ApiConfig', 'crispy_forms', 'admin_honeypot', 'rest_framework', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'users.middleware.OneSessionPerUserMiddleware') Traceback (most recent call last): File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Programs\Django\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1704, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1390, in response_action response = func(self, request, queryset) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\actions.py", line 28, in delete_selected deletable_objects, model_count, perms_needed, protected = modeladmin.get_deleted_objects(queryset, request) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1826, in get_deleted_objects return get_deleted_objects(objs, request, self.admin_site) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 151, in get_deleted_objects to_delete = collector.nested(format_callback) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 211, in nested roots.extend(self._nested(root, seen, format_callback)) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 195, in _nested children.extend(self._nested(child, seen, format_callback)) File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 197, in _nested ret = [format_callback(obj)] File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 126, in format_callback no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), obj) Exception Type: TypeError at /admin/users/customuser/ Exception Value: __str__ returned non-string (type CustomUser) 可以完成与上述相同的操作。参见javadoc

  

便捷的方法可以轻松创建简单的{@link RepositoryRestConfigurer}实例,而这些实例只想调整{@link RepositoryRestConfiguration}。

我在their integration tests之一中找到了用法

因此,到目前为止,以下方法将更加更新:

RepositoryRestConfigurer.withConfig

答案 4 :(得分:0)

这是一个好方法。

@Projection(name = "customBook", types = { Book.class }) 
public interface CustomBook {
 
    @Value("#{target.id}")
    long getId(); 
    
}

信用:https://www.baeldung.com/spring-data-rest-projections-excerpts