【问题标题】:Abstract domain classes in GORM: how to deal with static GORM methodsGORM 中的抽象域类:如何处理静态 GORM 方法
【发布时间】:2013-08-01 10:43:11
【问题描述】:

目前正在为此苦苦挣扎。

我希望能够使用抽象域类来使我能够使用一些通用代码来执行一些常用的操作。

我的问题是,很多 GORM 操作都是域类上的静态方法,这很困难。想知道这些方法是否有任何非静态等价物,例如我可以使用的“withTransaction”“findById”等。或者是否有任何“常规魔法”可以使用?

顺便说一句,我在 grails 之外使用 GORM,所以我认为我无法访问“static transactional=true”服务设置。

任何帮助将不胜感激。

抽象领域类:

@Entity
public abstract class Entity<K> {
    public abstract String toNiceString();
    public K id;

    public K getId(){
        return id;
    }

    public void setId(final K id){
        this.id = id;
    }
}

和一个示例具体类:

@Entity
@EqualsAndHashCode
class Person extends Entity<String> {
    String name
    String summary
    LocalDate birthDate
    LocalDate deathDate
    String occupations

    ...
}

以及一些我希望能够在某些域对象中重用的通用代码,但当然 T.xxxx() 静态方法不起作用。

public abstract class AbstractParser<T extends Entity> {

    protected void parseAndSavePages(){

        //Do some parsing
        ...

        T.withTransaction {
            if(T.findEntityById(entity.id)){
                println "Already exists!";
            } else {
                entity.save(failOnError: true);
            }
        }
    }
}

【问题讨论】:

    标签: grails groovy grails-orm


    【解决方案1】:

    与在 Java 中一样,答案很可能涉及将 Class 对象传递给 AbstractParser 构造函数。

    public abstract class AbstractParser<T extends Entity> {
    
        protected Class<T> entityClass
    
        protected AbstractParser(Class<T> entityClass) {
            this.entityClass = entityClass
        }
    
        protected void parseAndSavePages(){
    
            //Do some parsing
            ...
    
            // Groovy treats instance method calls on a Class object as calls
            // to static methods of the corresponding class
            entityClass.withTransaction {
                if(entityClass.findEntityById(entity.id)){
                    println "Already exists!";
                } else {
                    entity.save(failOnError: true);
                }
            }
        }
    }
    
    class PersonParser extends AbstractParser<Person> {
        public PersonParser() {
            super(Person)
        }
    }
    

    【讨论】:

    • 太棒了。工作了一个款待。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多