具有复合主键的JavaSpring数据rest
我将spring数据rest用于crud。但是当实体具有复合主键时,我不知道如何通过提供主键来获取实体
河流等级:
@Entity
public class River {
private RiverPK id;
private Double length;
private Timestamp date;
private String comment;
@Basic
@Column(name = "length")
public Double getLength() {
return length;
}
public void setLength(Double length) {
this.length = length;
}
@Basic
@Column(name = "date")
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
@Basic
@Column(name = "comment")
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Id
public RiverPK getId() {
return id;
}
public void setId(RiverPK id) {
this.id = id;
}
}
RiverPK等级:
@Embeddable
public class RiverPK implements Serializable {
private String name;
private int upcode;
private int downcode;
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "upcode")
public int getUpcode() {
return upcode;
}
public void setUpcode(int upcode) {
this.upcode = upcode;
}
@Column(name = "downcode")
public int getDowncode() {
return downcode;
}
public void setDowncode(int downcode) {
this.downcode = downcode;
}
}
河刀级:
@RepositoryRestResource(path = "river")
public interface RiverDAO extends JpaRepository<River, RiverPK> {
}
然后,我可以通过调用gethttp://localhost:8080/river/获取河流数据,还可以通过调用posthttp://localhost:8080/river/{river json}为db创建新实体
河流是:
id": {
"name": "1",
"upcode": 2,
"downcode": 3
},
"length": 4.4,
"date": 1493740800000,
"comment": "6"
}
在spring数据rest文档中,它应该能够调用getlocalhost:8080/river/1(主键)来获取主键为1的实体。当实体只有一个主键时,这可以工作。但我的实体river具有复合主键RiverPK。如果我调用getlocalhost:8080/river/{name='1',upcode=2,downcode=3},它将返回一个错误“找不到能够从[java.lang.String]类型转换为[com.example.db.entity.RiverPK]类型的转换器”,这意味着spring将{name='1',upcode=2,downcode=3}用作字符串,而不是RiverPK类型
问题是如何像其他普通实体一样使用复合主键调用get\put\delete
# 1 楼答案
有一个jira问题,你可以看看: https://jira.spring.io/browse/DATAREST-598
这个评论对你来说可能特别有趣
https://jira.spring.io/browse/DATAREST-598?focusedCommentId=117740&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-117740
在这里,您还可以找到一个样本项目的github link。它使用BackendIdConverter将复合键转换为字符串并返回。所以诀窍是将复合id转换为可以用作路径段的字符串
这个答案对你来说可能也很有趣https://stackoverflow.com/a/31830586/5371736