现在我在数据库,用户,喜欢和评论中有三个表,一个用户可以有很多喜欢和评论。在这种情况下,我使用JPA通过JAVA EE删除MYSQL中的记录。 但是当我试图删除喜欢和评论中的特定记录时。首先,我应该找到" likeid"和" commentid",代码如下所示。
public List<Like> findUser(Integer UserId){
em = factory.createEntityManager();
em.getTransaction().begin();
User user = em.find(User.class, UserId);
em.getTransaction().commit();
em.close();
List<Like> likes = new ArrayList<Like>();
likes=user.getLikes();
return likes;
}
public Like findLikebystyleid(String styleid,List<Like> likes)
{
for (int i = 0; i < likes.size(); i++) {
String temp=likes.get(i).getStyleid();
if(temp.equals(styleid))
{
return likes.get(i);
}
}
return null;
}
然后我发现&#34; likeid&#34;
public Integer Getremoveid(Integer userid,String styleid)
{
List<Like> likes = new ArrayList<Like>();
Like like=new Like();
likes=findUser(userid);
like=findLikebystyleid(styleid,likes);
try {return like.getId();
}
catch(Exception E){}
return -1;
}
最后我用em删除数据库中的记录。
public List<Like> removelike (Integer id)
{
List<Like> likes = new ArrayList<Like>();
em = factory.createEntityManager();
em.getTransaction().begin();
Like like=new Like();
try{
like=em.find(Like.class, id);
em.remove(like);
Query query = em.createQuery("select like from Like like");
likes = query.getResultList();
em.getTransaction().commit();
em.close();
return likes;
}
catch(Exception e){}
return null;
}
但是记录仍然存在于数据库中。我不知道为什么因为我在评论中实现了几乎相同的代码,所以可以删除记录。 评论代码如下所示:
public List<Comment> findCommentsbyUser(Integer UserId){
em = factory.createEntityManager();
em.getTransaction().begin();
User user = em.find(User.class, UserId);
em.getTransaction().commit();
em.close();
List<Comment> comments = new ArrayList<Comment>();
comments=user.getComments();
return comments;
}
public Comment findbystyleid(String styleid,List<Comment> comments)
{
for (int i = 0; i < comments.size(); i++) {
String temp=comments.get(i).getStyleid();
if(temp.equals(styleid))
{
return comments.get(i);
}
}
return null;
}
public Integer Getremoveid(Integer userid,String styleid)
{
List<Comment> comments = new ArrayList<Comment>();
Comment comment=new Comment();
comments=findCommentsbyUser(userid);
comment=findbystyleid(styleid,comments);
try {Integer id=comment.getId();
return id;
}
catch(Exception E){}
return -1;
}
public List<Comment> removecomment (Integer id)
{
List<Comment> comments = new ArrayList<Comment>();
em = factory.createEntityManager();
em.getTransaction().begin();
Comment comment=new Comment();
try{
comment = em.find(Comment.class, id);
em.remove(comment);
Query query = em.createQuery("select comment from Comment comment");
comments = query.getResultList();
em.getTransaction().commit();
em.close();
return comments;
}
catch(Exception e){}
return null;
}
我不知道为什么会这样,这让我发疯了。有人可以帮帮我吗?
答案 0 :(得分:0)
因为您需要先提交以便更改真正反映在数据库中...如果是注释,则您提交了em.getTransaction().commit();
,而不是Likes的情况