2

我一直在探索 Spring Boot (1.2.4) 以使用 H2 和 Jackson 创建一个简单的 RESTful 存储库。

像其他人一样,我注意到,默认情况下,@Id 字段不在返回的 Json 中(如本问题所述:在将应用程序迁移到 Spring Boot 后使用 Spring Data Rest 时,我观察到带有 @Id 的实体属性不再编组为 JSON)。

所以我想调整配置以包含它们。

但我无法让这一切正常工作。

基本实体类:

@Entity
public class Thing {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id; //I want this to appear in the RESTful JSON

    private String someInformation;

    protected Thing(){};

    public String getSomeInformation() { return someInformation; }

    public void setSomeInformation(String someInformation) { this.someInformation = someInformation; }

}

基本存储库接口:

public interface ThingRepository extends PagingAndSortingRepository<Thing, Long> {    
    List<Thing> findBySomeInformation(@Param("SomeInformation") String someInformation);
}

简单的启动应用程序:

@ComponentScan
@EnableAutoConfiguration
public class Application {    
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }    
}

还有我的配置类:

@Configuration
public class RepositoryRestMvcConfig extends SpringBootRepositoryRestMvcConfiguration {     
    @Override
    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Thing.class);
    }        
}

我可以从使用 --debug 运行 Spring Boot(如http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html中所述)看到我的配置已经找到了,但似乎没有任何效果。

4

1 回答 1

0

Jackson 在类的 getter/setter 上工作,而不是成员变量本身。因此,要确保 id 在 JSON 中,只需为其添加一个 getter:

@Entity
public class Thing {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id; //I want this to appear in the RESTful JSON

    private String someInformation;

    protected Thing(){};

    //this is what is needed
    public long getId() { return id; }

    public String getSomeInformation() { return someInformation; }

    public void setSomeInformation(String someInformation) { this.someInformation = someInformation; }

}
于 2016-12-20T11:59:11.887 回答