【发布时间】:2017-08-24 00:20:37
【问题描述】:
我在 db 中有 3 个表
培训
- training_id (pk)
user_profile
- profile_id (pk)
-training_profile(复合表)
- training_id
- profile_id
我已经在 user_profile 表中记录了 profile_id=44 并想为培训表创建新记录,并将这个新培训与已经存在的 id 为 44 的 user_profile 记录相关联,但在将发布数据保存到培训表之后但它没有插入到查找表 user_training 中。
我的项目类别是
- 培训班
@Entity
@Table(name = "training", schema = "public")
public class Training implements java.io.Serializable {
@Id @GeneratedValue
@Column(name = "training_id", unique = true, nullable = false)
private Long trainingId;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "trainings")
private Set<UserProfile> userProfiles = new HashSet<UserProfile>(0);
@Column(name = "training_subject", length = 200)
private String trainingSubject;
public Training() {
}
public Long getTrainingId() {
return this.trainingId;
}
public void setTrainingId(Long trainingId) {
this.trainingId = trainingId;
}
public String getTrainingSubject() {
return this.trainingSubject;
}
public void setTrainingSubject(String trainingSubject) {
this.trainingSubject = trainingSubject;
}
public Set<UserProfile> getUserProfiles() {
return this.userProfiles;
}
public void setUserProfiles(Set<UserProfile> userProfiles) {
this.userProfiles = userProfiles;
}
}
-
用户资料
@实体 @Table(name = "user_profile", schema = "public")
公共类 UserProfile 实现 java.io.Serializable {@Id @GeneratedValue @Column(name = "profile_id", unique = true, nullable = false) private Long profileId; @Column(name = "profile_description") private String profileDescription; @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }) @JoinTable(name = "user_training", schema = "public", joinColumns = { @JoinColumn(name = "profile_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "training_id", nullable = false, updatable = false) }) private Set<Training> trainings = new HashSet<Training>(0); public UserProfile() { } public String getProfileDescription() { return this.profileDescription; } public void setProfileDescription(String profileDescription) { this.profileDescription = profileDescription; } public Set<Training> getTrainings() { return this.trainings; } public void setTrainings(Set<Training> trainings) { this.trainings = trainings; }}
我得到回应
响应显示新的训练记录插入到 training_id 为 67 的表中 未找到此新保存的培训的关联
它再次为培训创建了新记录,并且与现有用户配置文件无关,我发布 curl -i -X POST -H "Content-Type:application/json" -d "{ \"trainingSubject\" : \" Oracle\", \"userProfiles\":[\"/userProfiles/44\"] }" http://localhost:8080/api/trainings
【问题讨论】:
-
您可以编辑您的问题并进行一些更正,然后重试吗?将
@Id @GeneratedValue放在id 字段前面的正确位置。在Training和UserProfile中。 -
GET http://localhost:8080/api/userProfiles/44确实返回了什么? -
localhost:8080/api/userProfiles/44,请检查我是否添加了有问题的屏幕截图
标签: spring spring-boot spring-data-jpa spring-data-rest