@ManyToMany Hibernate 注释中正确的 CascadeType 是什么?

What is the correct CascadeType in @ManyToMany Hibernate annotation?

我正在尝试在 Hibernate 中为瞬态操作解决方案架构建模,但我不确定如何从模型中获取我想要的对象图和行为。

table 结构使用关联 table(多对多)为操作创建用户列表:

Operation     OperationUsers      Users
op_id         op_id               user_id
...           user_id             ...

在使用 hibernate 注释对持久性 class Operation.java 进行建模时,我创建了:

@ManyToMany(fetch=FetchType.LAZY)
@JoinColumn(name="op_id")
public List<User> users() { return userlist; }

到目前为止,我有以下问题:

  1. 当用户从列表中删除时,如何避免休眠
    从用户 table 中删除用户?它应该被删除
    来自相关 table,而不是用户 table。我看不到有效的 CascadeType 来完成这个。
  2. 我是否需要在方法体中添加更多内容?
  3. 我需要添加更多注释参数吗?
  4. 我希望这样做而不 与用户class 打交道。 请告诉我,我不必搞乱 User.java!

这可能是我想多了,但这就是学习的本质......在此先感谢您提供的任何帮助!

来自文档:

Hibernate defines and supports the following object states:

*Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).

*Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.

*Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

this answer 中所述,您可以使用 Session.evict() 分离您的实体以防止休眠更新数据库或简单地克隆它并在副本上进行所需的更改。

事实证明,我的主要问题(#1 和主题)的具体答案是:"Do not specify any CascadeType on the property."

答案在 the answer to this question 中略有提及。