I can't insert a Tag associated to a post with ManyToMany relation in JPA. I keep on having an error saying that my Set of Tags in Post entity is NULL, however i checked that I've correctly created. Here is the sample of codes for this part. When I try to add a tag I get an error saying that the Tags 's Set in my Post Entity is NULL Post Entity:
@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;
}
Tag Entity :
@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);
}
*
ERROR:
É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)
An managed entity is instrumentalized by the persistence provider, so their fields are in a sort of intercepted state.
In your case, the direct access you've made is accessing a nulled pointer tags of your entity. Ideally, the code should access lists using the getter correspondent fields.
Your code should change to:
public void addTag(Tag tag) {
getTags().add(tag);
tag.getPosts().add(this);
}
Even in this case, you can face a NPE or specific exceptions if the underlying persistence provider already evicted the entity from the EntityManager - making it not managed.
As you are using Apache Tomee 8, I suggest you should create a DAO @Transactional annotated function to add a tag to a post and call it from your servlet. So your DAO would have the following code:
@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;
}
Hope it helps!