前言
为了懒省事,使用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