我在Hibernate中有一个希望很简单的问题。我有用户和项目。 users_projects(在我的例子中是user_project_association)有一个额外的属性" role"说用户是项目负责人还是普通用户。
@OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@LazyCollection(LazyCollectionOption.EXTRA)
private Set<UserProjectAssociation> userProjectAssociations = new HashSet<>();
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_project_role",
joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
@WhereJoinTable(clause = "role_id=7")
@Setter(AccessLevel.NONE)
private Set<User> projectLeaders = new HashSet<>();
@ManyToMany
@JoinTable(name = "user_project_role",
joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
@LazyCollection(LazyCollectionOption.EXTRA)
@Setter(AccessLevel.NONE)
private Set<User> users = new HashSet<>();
如果我尝试通过&#34; getEntityManager()删除项目.remove(persistentInstance);&#34;我可以在日志中看到这个sql语句:
Hibernate:
/* delete collection com.XXX.core.model.Project.users */ delete
from
user_project_role
where
project_id=?
Hibernate:
/* delete collection com.XXX.core.model.Project.projectLeaders */ delete
from
user_project_role
where
project_id=?
and (
role_id=7
)
Hibernate:
/* delete com.XXX.core.model.UserProjectAssociation */ delete
from
user_project_role
where
id=?
和错误消息:
2016-05-25 10:05:57 INFO AbstractBatchImpl:208 - HHH000010: On release of batch it still contained JDBC statements
并且没有删除任何内容。有没有人有想法删除我的项目?
非常感谢:)
答案 0 :(得分:0)
PUH。我找到了(或者)解决方案。它并不是很优雅,但它有效:
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_project_role",
joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
@WhereJoinTable(clause = "role_id=7")
@SQLInsert(sql = "insert into user_project_role (project_id, user_id, role_id) values (?, ?, 7)")
@SQLDelete(sql = "delete from user_project_role where project_id=? and user_id=? and role_id = 7")
@Setter(AccessLevel.NONE)
private Set<User> projectLeaders = new HashSet<>();
@ManyToMany
@JoinTable(name = "user_project_role",
joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
@LazyCollection(LazyCollectionOption.EXTRA)
@WhereJoinTable(clause = "role_id=8")
@SQLInsert(sql = "insert into user_project_role (project_id, user_id, role_id) values (?, ?, 8)")
@Setter(AccessLevel.NONE)
private Set<User> projectUsers = new HashSet<>();
所以我删除了userProjectAssociations属性并添加了自定义的@SQLInsert和@SQLDelete语句。
如果我想让所有用户包括普通用户和项目负责人,我会使用这种方法:
public Set<User> getAllUsers() {
Set<User> allUsers = new HashSet<>();
allUsers.addAll(projectLeaders);
allUsers.addAll(projectUsers);
return allUsers;
}