我正在做一个新的简单的抽认卡项目。总结:一个用户可以有多个抽认卡,所以用户和抽认卡之间的关系是oneToMany。当我尝试创建一个新的抽认卡时,我得到以下错误:
2023-08-27T09:03:14.399+02:00 WARN 31571 --- [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Failure while trying to resolve exception [org.springframework.http.converter.HttpMessageNotWritableException]
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.checkCommitted(ResponseFacade.java:503) ~[tomcat-embed-core-10.1.11.jar:10.1.11]
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:347) ~[tomcat-embed-core-10.1.11.jar:10.1.11]
.
.
.
字符串
我的Java类如下:
User.class:
@Data
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "userId_generator")
private Integer id;
private String username;
private String firstName;
private String lastName;
private String password;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private List<Flashcard> flashcards;
@CreationTimestamp
private Instant createdOn;
@UpdateTimestamp
private Instant updatedOn;
}
型
Flashcard.class:
@Entity
@Data
public class Flashcard {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "flashcardId_generator")
private int id;
private String name;
private String description;
@ManyToOne( fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private User user;
}
型
FlashcardController.class:
@RestController
public class FlashcardController {
@Autowired
FlashcardRepository flashcardRepository;
@Autowired
UserRepository userRepository;
...some code with get method
@PostMapping("/users/{id}/flashcards")
public ResponseEntity<Flashcard> createFlashcard(@PathVariable("id") int userId, @RequestBody Flashcard flashcard) {
Flashcard _flashcard = userRepository.findById(userId).map(user -> {
flashcard.setUser(user);
return flashcardRepository.save(flashcard);
}).get();
return new ResponseEntity<>(_flashcard, HttpStatus.CREATED);
}
}
型
当我删除
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private List<Flashcard> flashcards;
型
从User.class,我可以创建新的抽认卡。然而,当我发送一个带有userId的get请求时,我想看到所有属于他的抽认卡。
1条答案
按热度按时间nfg76nw01#
在你的代码中有两个问题,我可以看到:
1.在控制器调用周围没有事务,因此,您试图持久化引用分离的
User
的Flashcard
实体1.关联的任何一端都没有标记为
@JsonIgnore
,所以JSON序列化失败,如果spring.jpa.open-in-view
是true
,则为StackOverflowError
,否则为LazyInitializationException
(这可能是核心问题,但我不能确定,因为根本原因没有包含在您提供的堆栈跟踪中)一个简单的方法来做你想做的事情是:
字符串
加上
型
由于您将两边都标记为lazy,因此两边可能都需要
@JsonIgnore
。顺便说一句,
Flashcard.user
上的@OnDelete(action = OnDeleteAction.CASCADE)
并没有真正的意义(它说的是'当用户的一个闪存卡被删除时,请删除整个用户',我很确定这不是你的意图)