![](/img/trans.png)
[英]Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
[英]Spring Data REST javax.persistence.RollbackException: Error while committing the transaction
我有两个实体:
@Data
@Entity(name = "users")
@NoArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode
public User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id", unique = true, nullable = false)
private Integer userId;
private String userName;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
@JoinColumn(name = "user_id")
@Fetch(value = FetchMode.SUBSELECT)
private List<Degree> degreeList;
}
和
@Data
@Entity(name = "degrees")
@NoArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode
public Degree {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id", unique = true, nullable = false)
private Integer degreeId;
private String degreeTitle;
}
RestResources 是:
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRestRepository extends CrudRepository<User, Integer> {
}
接着:
@RepositoryRestResource(collectionResourceRel = "degrees", path = "degrees")
public interface DegreeRestRepository extends CrudRepository<Degree, Integer> {
}
我必须使用https://www.myhost.com/api/users/{userId}/degreeList
端点在 foo 的barList
中添加新bar
,如图所示:
但我得到:
{
"timestamp": "2020-04-17T05:16:51.520+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction",
"path": "/api/users/4/degreeList"
}
我已经搜索并发现我必须保存Degree
然后更新degreeList
,我该怎么做,请指导
Spring 数据 REST 是基于 URI 的(遵循 HATEOAS 规则)。 如果您想将“degree”添加到“degreeList”,确实您首先需要创建学位:
HTTP POST 到
https://www.myhost.com/api/degrees
请求正文必须是内容类型application/json
之后,您会在响应中取回学位 ID。 您使用此 ID 将度数添加到列表中:
HTTP POST 到
https://www.myhost.com/api/users/{userId}/degreeList
重要提示:这次请求的内容类型是text/uri-list
! 正文必须是纯文本,并且应该只包含 URI
https://www.myhost.com/api/degrees/{degreeId}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.