My Spring Data存储库被默认为默认的@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;
.....
我希望House obkect作为Flat对象的嵌入部分以JSON形式返回,但只获取到房子的URL
/ repository / flats / 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"
}
}
}
同时,用户角色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>();
.....
请求:/ repository / users / 5
{
"id" : 5,
"login" : "op898",
"email" : "op20140603@gmail.com",
"password" : "c6172176f8f5d7e660eb4dcfad07a6ca",
"roles" : [ {
"roleName" : "OPERATOR"
} ],
"_links" : {
"self" : {
"href" : "http://localhost:8080/kap/repository/users/5"
}
}
}
除了关系类型之外,我无法弄清楚差异。任何的想法 ? 谢谢
答案 0 :(得分:2)
好吧,我找到了原因,但仍然不明白是否可以配置。
对于用户 - 角色关系,Role作为User的嵌入式JSON对象返回,因为没有为Role实体定义存储库。 但是House和Flat都有相应的JpaRepository,并且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"
}
}
}
但这不是解决方案,因为我还需要House Data实体的Spring Data REST存储库。有任何想法吗 ?
答案 1 :(得分:2)
再次回答自己。 最后使用org.springframework.data.rest.core.config.Projection解决问题 我将经典HAL作为默认设置,并创建了暴露Flat.House属性的自定义投影。