我有两个表:配方表和帐户表。配方表存储了许多配方。account 表存储了一些用户帐号。一个用户可以与 0 个或多个配方相关联。当用户喜欢食谱时,该用户与该食谱相关联。为了记录这种关联,我创建了一个名为 LikedRecipe 的表。
这些是每个表的列:
- 配方:身份证,姓名。Id 是主键。
- 账号:邮箱、密码。电子邮件是主键。
LikedRecipe:身份证、姓名、电子邮件。id 是主键。
@Entity @Table(name = "Recipe") public class Recipe { private Set<Account> account; private Long id; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "LikedRecipe", joinColumns = @JoinColumn(name = "recipeId"), inverseJoinColumns = @JoinColumn(name = "email")) public Set<Account> getAccount() { return account; } public void setAccount(Set<Account> account) { this.account = account; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } } @Entity @Table(name = "Account") public class Account implements Serializable { private Set<Recipe> likedRecipes = new HashSet<Recipe>(); private String email; @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }) @JoinTable(name = "LikedRecipe", joinColumns = @JoinColumn(name = "email"), inverseJoinColumns = @JoinColumn(name = "recipeId")) public Set<Recipe> getLikedRecipes() { return likedRecipes; } public void setLikedRecipes(Set<Recipe> likedRecipes) { this.likedRecipes = likedRecipes; } @Column(name = "email") @Id public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
我写了一个方法来删除帐户和食谱之间的关联:
public void unlikeARecipe(String email, Long recipeId){
Query query = entityManager
.createQuery("delete from LikedRecipe where recipeId = :recipeId and email = :email");
query.setParameter("recipeId", recipeId);
query.setParameter("email", email);
query.executeUpdate();
}
这个方法并没有从 LikedRecipe 表中删除记录,直到我在方法末尾添加了这行代码:
entityManager.clear();
根据 JPA API 文档,clear 方法清除持久性上下文,导致所有托管实体分离。
我的问题是分离是什么意思?而且,分离对象如何使上述方法从 LikedRecipe 表中删除记录?我是否以正确的方式使用 clear 方法?
谢谢你。