Spring data rest 如何显示主键

How to expose the resourceId with Spring-Data-Rest?

Spring-Data-Rest is a quite new project in the Spring family of pivotal. The intention of this project is to reduce the boilercode of controllers and services when you need only CRUD methods on an entity for your REST resources. – Quote from project page is “Spring-Data-Rest makes it easy to expose JPA based repositories as RESTful endpoints.”

One requirement I had was to expose the CRUD identifier and database primary key which is annotated with @Id. In my case that was needed because the field was functional required. For that I had to expose it because at the standard configuration the ID field is only visible on the resource path, but not on the JSON body.

 

To expose it you need to configure your RepositoryRestMvcConfiguration like that:

1
2
3
4
5
6
7
8
@Configuration
public class MyCoolConfiguration extends RepositoryRestMvcConfiguration {
 
     @Override
     protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
         config.exposeIdsFor(FooEntity. class );
     }
}

The entity class could look like that:

1
2
3
4
5
6
7
8
9
@Entity
public class FooEntity {
 
     @Id
     @GeneratedValue (strategy= GenerationType.AUTO)
     Long id;
 
     String name;
}

With this configuration you will receive your entity id back.

1
2
3
4
5
6
7
8
9
{
   "_links" :{
   "self" :{
   }
},
   "id" :1,
   "name" : "bar"
}

Additional Comment from a Spring-Developer: URI stands for unique, resource, *identifier* – The URI *is* the id. What I expose here is a database internals.

 

转自:How to expose the resourceId with Spring-Data-Rest?

 

另一种:

 

package net.huuat.micro.base.schedule;

import net.huuat.micro.base.schedule.domain.TJobConf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;

@Configuration
public class SpringDataRestConfig {
	@Bean
    public RepositoryRestConfigurer repositoryRestConfigurer() {

        return new RepositoryRestConfigurerAdapter() {
            @Override
            public void configureRepositoryRestConfiguration(
                    RepositoryRestConfiguration config) {
                config.exposeIdsFor(TJobConf.class);
            }
        };
    }

}

 

  

 

转载于:https://www.cnblogs.com/kms1989/p/5809187.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值