无法在 JPA 中插入 ManyToMany 关系

Can't insert in ManyToMany relation in JPA

我无法在 JPA 中插入与具有 ManyToMany 关系的 post 关联的标签。我一直有一个错误说我在 Post 实体中的标签集是 NULL,但是我检查了我是否正确创建了。这是这部分的代码示例。当我尝试添加标签时,我收到一条错误消息,指出 Post 实体中的标签集为 NULL Post实体:

@Entity
@Table(name = "posts")
public class Post implements Serializable  {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "author", nullable = false)
    private String auteur;

    @Column(nullable = false)
    private String content;

    @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
    @JoinTable(name = "post_tag",
            joinColumns = { @JoinColumn(name = "post_id") },
            inverseJoinColumns = { @JoinColumn(name = "tag_id") })    
       // private List<Tag> tags = new ArrayList<>();
     private Set<Tag> tags= new HashSet<>();
    public Post() {
        super();
    }

        public void addTag(Tag tag) {
         if(this.tags != null) {
                this.tags.add(tag);
                tag.getPosts().add(this);
            } 

        }
        public void removeTag(Tag tag) {
            tags.remove(tag);
            tag.getPosts().remove(this);
        }

    public Set<Tag> getTags() {
            return tags;
        }

    @JsonIgnore
        public void setTags(Set<Tag> tags) {
            this.tags = tags;
        }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Post)) return false;
        //return id != null && id.equals(((Post) o).getId());
        return this != null && this.equals(((Post) o).getId());
    }

    @Override
    public int hashCode() {
        return 31;
    }       

标记实体:

    @Entity
@Table(name = "tag")
public class Tag implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @Column(nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(nullable = false)
    private String content;


     @ManyToMany(mappedBy = "tags",  cascade= {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
    //  @ManyToMany(mappedBy = "tags")
        private Set<Post> posts = new HashSet<>();
    public Tag() {
        super();
    }

    public Tag(String content) {
        //this.id = id;
        this.content = content;
        //this.posts = new HashSet<Post>();
    }
public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Set<Post> getPosts() {
        return posts;
    }

    @JsonIgnore
    public void setPosts(Set<Post> posts) {
        this.posts = posts;
    }
**Servlet to ADD Tag to Post:**


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tag_cont = request.getParameter("NewTag");

        int id = Integer.parseInt(request.getParameter("postId"));
        if (!tag_cont .isEmpty()) {

                Tag t = new Tag(tag_cont);
                Post post = postDAO.findById(id);
                post.addTag(t);



            }
*

错误:

   État HTTP 500 – Erreur interne du serveur
Type Rapport d'exception

description Le serveur a rencontré une erreur interne qui l'a empêché de satisfaire la requête.

exception

java.lang.NullPointerException
    com.reddit.entities.Post.addTag(Post.java:106)
    com.projet.servlet.AddTagPost.doPost(AddTagPost.java:43)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
note La trace complète de la cause mère de cette erreur est disponible dans les fichiers journaux de ce serveur.

Apache Tomcat (TomEE)/9.0.30 (8.0.1)

托管实体由持久性提供程序工具化,因此它们的字段处于某种拦截状态。

在您的例子中,您所做的直接访问是访问实体的空指针标记。理想情况下,代码应该使用 getter 相应字段访问列表。

您的代码应更改为:

public void addTag(Tag tag) {
    getTags().add(tag);
    tag.getPosts().add(this);
}

即使在这种情况下,如果底层持久性提供程序已经将实体从 EntityManager 中逐出 - 使其不受管理,您也可能面临 NPE 或特定异常。

当您使用 Apache Tomee 8 时,我建议您应该创建一个 DAO @Transactional 注释函数以将标记添加到 post 并从您的 servlet 调用它。所以您的 DAO 将具有以下代码:

@Transactional
public Post addTag(Integer postId, String tagContents) {
    Post p = findById(postId); // assuming it exists, null checks should be made
    Tag t = new Tag(tagContents);
    // You may call p.addTag(t) here, as defined above, instead of the following code
    p.getTags().add(t);
    t.getPosts().add(p);
    return p;
}

希望对您有所帮助!