カスケードと多対多の関連付けに関する多くのトピックを読みましたが、特定の質問に対する答えを見つけることができませんでした。
UserProfiles と Roles の間に多対多の関係があります。UserProfile を削除すると、結合テーブル (userprofile2role) 内の関連レコードがデータベースによって削除されるので、実際の SQL 'ON DELETE CASCADE' アクションを使用します。これは可能ですか?何を試しても、Hibernate は常に ON DELETE 動作を指定せずに UserProfile テーブルを作成します。
UserProfile マッピング:
@Entity
public class UserProfile {
private Long id;
private Set<Role> roles;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public final Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// Note: CascadeType.ALL doesn't work for many-to-many relationships
@ManyToMany (fetch = FetchType.EAGER)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
役割のマッピング:
@Entity
public class Role {
private Long id;
private Set<UserProfile> userProfiles = new HashSet<UserProfile>();
@Id
@GeneratedValue
public final Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// CascadeType.REMOVE doesn't create ON CASCADE DELETE in SQL?
@ManyToMany(mappedBy = "roles", cascade = CascadeType.REMOVE)
public Set<UserProfile> getUserProfiles() {
return userProfiles;
}
public void setUserProfiles(Set<UserProfile> userProfiles) {
this.userProfiles = userProfiles;
}
}
残念ながら、これらのマッピングの結果の結合テーブルの SQL には、ON CASCADE DELETE 部分が含まれていません。UserProfile のロール コレクションと Role の userprofiles コレクションの両方で CascadeType.REMOVE 動作を設定しようとしましたが (ここに表示)、役に立ちませんでした。あなたの提案は大歓迎です:-)
CREATE TABLE `px_userprofile2role` (
`userprofile_id` BIGINT(20) NOT NULL,
`role_id` BIGINT(20) NOT NULL,
PRIMARY KEY (`userprofile_id`,`role_id`),
KEY `FK1C82E84191F65C2B` (`userprofile_id`),
KEY `FK1C82E8416203D3C9` (`role_id`),
CONSTRAINT `FK1C82E8416203D3C9` FOREIGN KEY (`role_id`) REFERENCES `px_role` (`id`),
CONSTRAINT `FK1C82E84191F65C2B` FOREIGN KEY (`userprofile_id`) REFERENCES `px_userprofile` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=latin1