Grails有很多关系关注

时间:2014-07-04 02:58:45

标签: grails

我有一个应用程序,其中所有者对象可以有许多帐户对象,而帐户对象可以有许多所有者对象。我想过用多对多的关系对它进行建模,但后来我意识到我可能还需要创建帐户对象,其中所有者无法立即确定,或者可能在将来创建帐户后创建。因此,我不相信我可以使用Grails多对多关系(我认为)。所以,我只是在Owner类中有一个属性,它是一个Account ID列表(这将是Owner's Accounts引用)和Account类中的一个属性,它是Owner ids的列表(这将是Account的业主参考)。有更好的想法吗?我觉得这太老式了,类似于C ++指针的做法。

2 个答案:

答案 0 :(得分:1)

您可以创建第三个域来解决此关系

class Owner{
    ...

    Set<Object> getObjects() {
        OwnerObject.findAllByOwner(this).collect { it.object } as Set // or replace with optimized criteria
    }
    ...
}

class Object{
    ...

    Set<Owner> getOwners() {
        OwnerObject.findAllByObject(this).collect { it.owner } as Set // or replace with optimized criteria
    }
    ...
}


class OwnerObject implements Serializable {

    Owner owner
    Object object

    boolean equals(other) {
        if (!(other instanceof OwnerObject)) {
            return false
        }
        other.owner?.id == owner?.id && other.object?.id == object?.id
    }

    static OwnerObject get(long ownerId, long objectId) {
        find 'from OwnerObject where owner.id=:ownerId and object.id=:objectId',
                [ownerId: ownerId, objectId: objectId]
    }

    static OwnerObject create(Owner owner, Object object, boolean flush = false) {
        new OwnerObject(owner: owner, object: object).save(flush: flush, insert: true)
    }

    static boolean remove(Owner owner, Object object, boolean flush = false) {
        OwnerObject instance = OwnerObject.findByOwnerAndObject(owner, object)
        if (!instance) {
            return false
        }
        instance.delete(flush: flush)
        true
    }

    static void removeAll(Owner owner) {
        executeUpdate 'DELETE FROM OwnerObject WHERE owner=:owner', [owner: owner]
    }

    static void removeAll(Object Object) {
        executeUpdate 'DELETE FROM OwnerObject WHERE object=:object', [object: object]
    }

    static mapping = {
        id composite: ['object', 'owner']
        version false
    }
}

答案 1 :(得分:1)

坦率地说,在我6年多的“Grails-career”中,我只使用过m2m关系一次。相反,o2m和动态查询的组合更容易实现和维护,并且通常更高效。