簡體   English   中英

錯誤 - 非空屬性引用 null 或瞬態值

[英]Error - not-null property references a null or transient value

我是 Spring 的新手。我根據兩個表之間的關系制作了一個 API,為此使用了 OneToMany 注釋,對於 API 測試,我有 postman。我的目標是將請求的數據保存在下面提到的兩個單獨的實體中. 當我嘗試在 postman 中發布數據時:1-3 個字段與 Post 實體相關,而文本字段屬於 Comment 實體(評論正在加入字段)

{
"title": "Post1",
"description": "Post 1 description",
"content": "Post 1 content",
"comments": [
    {
        "text": "Java best selling book"
    },
    {
        "text": "Exploring spring boot"
    }
]

}

我收到如下錯誤:

Hibernate: insert into posts (content, description, title) values (?, ?, ?)
2021-09-01 11:55:09.786 TRACE 9884 --- [nio-8089-exec-2] o.h.type.descriptor.sql.BasicBinder      
: binding parameter [1] as [VARCHAR] - [Post 1 content]
2021-09-01 11:55:09.786 TRACE 9884 --- [nio-8089-exec-2] o.h.type.descriptor.sql.BasicBinder      
: binding parameter [2] as [VARCHAR] - [Post 1 description]
2021-09-01 11:55:09.786 TRACE 9884 --- [nio-8089-exec-2] o.h.type.descriptor.sql.BasicBinder      
: binding parameter [3] as [VARCHAR] - [Post1]
2021-09-01 11:55:09.815 ERROR 9884 --- [nio-8089-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    
: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
[Request processing failed; nested exception is 
org.springframework.dao.DataIntegrityViolationException: not-null property references a null 
or transient value : com.techspring.entity.Comment.post; nested exception is 
org.hibernate.PropertyValueException: not-null property references a null or transient value : 
com.techspring.entity.Comment.post] with root cause

我的 MVC 如下:

郵編java

@Entity
@Table(name = "posts")
public class Post {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String title;
  private String description;
  private String content;
  @OneToMany(cascade = CascadeType.ALL,
        fetch = FetchType.LAZY,
        mappedBy = "post")
  private Set<Comment> comments = new HashSet<>();

  GET, SET;

評論.java

@Entity
@Table(name = "comments")
public class Comment {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String text;

  @ManyToOne(fetch = FetchType.LAZY, optional = false)
  @JoinColumn(name = "post_id", nullable = false)
  private Post post;

  Get, Set;

PostController.java

RestController 公共 class PostController {

@Autowired
private PostRepository postRepository;

@PostMapping("/posts")
public Post createPost(@Valid @RequestBody Post post) {
    return postRepository.save(post);
}      

CommentController.java

@RestController
public class CommentController {

@Autowired
private CommentRepository commentRepository;

@Autowired
private PostRepository postRepository;


@PostMapping("/posts/{postId}/comments")
public Comment createComment(@PathVariable (value = "postId") Long postId,
                             @Valid @RequestBody Comment comment) {
    return postRepository.findById(postId).map(post -> {
        comment.setPost(post);
        return commentRepository.save(comment);
    }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));

感謝您的幫助。

你這樣做的方式Comment comment<\/code>是一個新的臨時實體,它與已經維護的post<\/code>實體相關。 在保存期間,第一次休眠將嘗試更新帖子以匹配該評論,但該評論尚不存在,因此失敗。

對您來說更好的工作流程如下。

返回帶有所有評論的帖子更有意義,並且只需將新評論附加到已經存在的帖子中。 這樣,hibernate 將首先創建評論實體,然后將其與已經存在且不會遇到任何問題的帖子相關聯。

@PostMapping("/posts/{postId}/comments")
public Post createComment(@PathVariable (value = "postId") Long postId,
                             @Valid @RequestBody Comment comment) {
    Optional<Post> postOpt = postRepository.findById(postId);
      if (postOpt.isPresent()) {
        comment.setPost(postOpt.get()); <----------------
        postOpt.get().getComments().add(comment);
        postRepository.save(postOpt.get());
        return postOpt.get();
      } else {
        throw new ResourceNotFoundException("PostId " + postId + " not found");
      }

   }

我有一個類似的問題,要解決它,您需要將父對象設置為子對象。 會是這樣的

post.getComments().stream().forEach(c -> c.setPost(post));

我有一個類似的問題,為了解決它,我必須將實體 Object 更改為可為空。

@Column( name = "dog", nullable = true ) private String dog;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM