Grails GORM关联未映射的异常

时间:2014-09-19 13:51:36

标签: exception grails associations gorm

我正在创建Grails 2.4.3应用并拥有以下域类:

class StockItem {
    String name
    BigDecimal wholesalePrice
    BigDecimal retailPrice
    BigDecimal profit

    static belongsTo = [ledger: Ledger]

    static constraints = {
        name minSize:3, maxSize:255
        wholesalePrice min:0.0, scale:2
        retailPrice min:0.0, scale:2
        retailPrice validator: { retailPrice, StockItem obj ->
            if (retailPrice < obj.wholesalePrice) {
                ['retailLessThanWholesale']
            }
        }
    }

    static mapping = { 
        profit(formula: 'RETAIL_PRICE - WHOLESALE_PRICE') 
    }
}

class Ledger {
    String name

    static hasMany = [clients: Client, invoices: Invoice, availableItems: StockItem, payments: Payment]

    static constraints = {
        name unique:true
    }
}

我有一个单元测试:

@Domain(StockItem)
@TestMixin(HibernateTestMixin)
class StockItemSpec extends Specification {
    void "Test profit calculation"() {
        when: "a stock item exists"
        StockItem i = new StockItem(name: "pencil", wholesalePrice: 1.50, retailPrice: 2.75)

        then: "profit is calculated correctly"
        i.profit == 1.25
    }

}

因此失败了:

Failure:  Test profit calculation(com.waldoware.invoicer.StockItemSpec)
|  org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is 
org.hibernate.MappingException: An association from the table stock_item refers to an unmapped class: com.waldoware.invoicer.Ledger

该应用程序似乎运行正常,我无法理解为什么此测试失败。任何想法都表示赞赏!

1 个答案:

答案 0 :(得分:2)

由于您的belongsToStockItem域类之间存在Ledger关联,因此您需要在测试中的Ledger注释中添加@Domain

@Domain([StockItem, Ledger])

这应该在初始化单元测试运行时时正确配置所需的域类。根据您的其他测试用例,您可能还需要在注释中加入ClientPayment