在Grails中使用多对多映射进行级联删除

时间:2013-05-31 11:05:40

标签: java hibernate grails gorm

我有关于多对多映射的问题。

[案例]

  • 帐户拥有社区(所有者)
  • 社区有许多帐户(成员)

当我删除社区实例时,所有者帐户也会被删除。

我不希望删除所有者帐户。

我的映射错了?

[域类]

class Account {

String name

static hasMany = [communities: Community]
static belongsTo = [Community]
}

class Community {

String name
Account owner

static hasMany = [members: Account]
}

[TestCode]

def admin = new Account(name: 'admin').save(flush:true)
def user = new Account(name: 'user').save(flush:true)

def c = new Community(name: 'TestCommunity')

c.owner = admin

c.addToMembers(admin)
c.addToMembers(user)            
c.save(flush:true)

c.removeFromMembers(user)
c.save(flush:true)

c.delete(flush:true)

[休眠日志]

Hibernate: insert into account (id, version, name) values (null, ?, ?)
Hibernate: insert into community (id, version, name, owner_id) values (null, ?, ?, ?)
Hibernate: update account set version=?, name=? where id=? and version=?
Hibernate: insert into community_members (community_id, account_id) values (?, ?)
Hibernate: update account set version=?, name=? where id=? and version=?
Hibernate: update community set version=?, name=?, owner_id=? where id=? and version=?
Hibernate: delete from community_members where community_id=? and account_id=?
Hibernate: delete from community_members where community_id=?
Hibernate: delete from community where id=? and version=?
Hibernate: delete from account where id=? and version=?          <== not expected !!

1 个答案:

答案 0 :(得分:0)

你必须提供等同于on delete set null映射

的休眠

已经有一个问题了。有关详细信息,请参阅How do I override the cascade delete for a relation in Grails GORM?