在Spring Data Rest中没有获取ManyToOne渴望关联



我的Spring数据存储库配置为默认的@RepositoryRestResource,没有任何自定义。

JPA实体:

@Entity
@Table(name = "flat")
public class Flat implements Serializable {
private static final long serialVersionUID = -7402659216552976109L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "flat_id")
private Integer id ;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "house_id", referencedColumnName="house_id",  insertable=false, updatable=false)
private House house;
@Column(name = "kad_num")
private String kadNum;

我希望房子对象在JSON中返回作为平面对象的嵌入部分,但只得到URL到房子

/repository/公寓/442991:

{
"kadNum" : "78:06:0002202:8981",
"sqrFull" : 52.7000,
"flatNum" : "311",
"_links" : {
    "self" : {
       "href" : "http://localhost:8080/kap/repository/flats/442991"
     },
    "house" : {
       "href" : "http://localhost:8080/kap/repository/flats/442991/house"
     }
  }
}

同时获取User-Role OneToMany关系,角色名:

@Entity
@Table(name = ""user"")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Integer id;
private String login;
private String email;
private String password;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id", nullable=false , updatable = false, insertable = true)
private Set<Role> roles = new HashSet<Role>();
  .....

请求:/仓库/用户/5

{
 "id" : 5,
 "login" : "op898",
 "email" : "op20140603@gmail.com",
 "password" : "c6172176f8f5d7e660eb4dcfad07a6ca",
  "roles" : [ {
    "roleName" : "OPERATOR"
  } ],
  "_links" : {
  "self" : {
  "href" : "http://localhost:8080/kap/repository/users/5"
}
}
}
除了关系类型,我看不出有什么不同。知道吗?谢谢你

嗯,我已经找到了原因,但仍然不明白是否可以配置。

对于User-Role关系,Role作为User的嵌入式JSON对象返回,因为没有为Role实体定义存储库。但是House和Flat都有对应的jparerepository,并且House在Flat JSON对象中只作为URL返回。似乎Spring Data REST总是在可能使用REST获取实体时自动将实体替换为JSON中的REST链接。一旦我从项目中删除了House存储库,Flat的JSON响应就变成了我想要的形式,嵌入了House:

{
  "house" : {
    "streetFull" : "KIMa pr.",
    "houseNum" : "1",
    "kadNum" : "78:06:0002202:3072",
    "building" : null,
    "liter" : "В",
    "sqrFull" : 10426.50,
    "sqrRooms" : 12868.10
  },
  "kadNum" : "78:06:0002202:9051",
  "sqrFull" : 43.8000,
  "flatNum" : "421",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/kap/repository/flats/442987"
    },
    "flats" : {
      "href" : "http://localhost:8080/kap/repository/flats/442987/flats"
    }
  }
}

但这不是一个解决方案,因为我需要Spring Data REST存储库也为House实体。有什么想法吗?

又是对自己的回答。最后通过使用org.springframework.data.rest.core.config.Projection解决了这个问题我将经典的HAL作为默认设置,并使用Flat创建自定义投影。房产暴露。

最新更新