Spring Data Rest如何暴露ID字段

前言

为了懒省事,使用Spring Data Rest来直接提供rest接口,重点遇到点小坑,记录一下。

记录

问题

entity:

@Entity
@Table(name = "db_table")
public class DBTable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer tableId;

    @Column
    private String tableName;

    @Column
    private String comment;
}

repository:

import com.lagou.platform.metadata.entity.DBTable;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created by Gim on 16/8/10.
 */
public interface DBTableRepository extends JpaRepository<DBTable, Integer> {

}

运行后,就会发现,没有tableId字段。

{
  "_embedded" : {
    "dBTables" : [ {
      "tableName" : "haha",
    }, {
      "tableName" : "haha111",
      ......
}

原因和解决

stackoverflow 上的解决方案,说的很清晰了。

I recently had the same problem and it’s because that’s how spring-boot-starter-data-rest works by default. See my SO question -> While using Spring Data Rest after migrating an app to Spring Boot, I have observed that entity properties with @Id are no longer marshalled to JSON

To customize how it behaves, you can extend RepositoryRestMvcConfiguration to expose IDs for specific classes.

@Configuration
public class RepositoryConfig extends RepositoryRestMvcConfiguration {
    @Override
    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Person.class);
    }
}

但是这种方案不爽的地方就是configureRepositoryRestConfiguration已经被标注废弃了,因此自己重新搞一个。

/**
 * 为了解决Spring Data Rest不暴露ID字段的问题。
 * 参考:http://tommyziegler.com/how-to-expose-the-resourceid-with-spring-data-rest/
 * Created by Dante on 2016/8/18.
 */
@Configuration
class SpringDataRestConfig {
    @Bean
    public RepositoryRestConfigurer repositoryRestConfigurer() {

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

2016-08-18 18:48:00

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值