Grails未按预期设置数据库

Grails未按预期设置数据库,grails,gorm,Grails,Gorm,嗨,这已经持续了好几个月了,我已经失去了所有的希望 我有3个域名的问题 产品由组件组成,每个组件都可以有替代产品 以下是我的模型: 产品: class Product { String name String comments static hasMany = [components:Components] } 组成部分: class Components { Product product static hasMany = [altern

嗨,这已经持续了好几个月了,我已经失去了所有的希望

我有3个域名的问题

产品由组件组成,每个组件都可以有替代产品

以下是我的模型:

产品:

 class Product {
     String name
     String comments
     static hasMany = [components:Components]
 } 
组成部分:

 class Components {
    Product product
    static hasMany = [alternatives:Alternatives]
 }
备选方案:

class Alternatives {
    Product product
}
要填充此内容,我正在分析excel电子表格,以下是执行此操作的代码:

Product st = new Product(
    name: row.getCell(0).getStringCellValue().toUpperCase(),
    comments: "test"
)
row.getCell(10).getStringCellValue().split("[|]").each {
    Product pro = Product.findByName(it.toUpperCase())
    if(pro) {
        Components c =  new Components(product: pro).save(flush:true)
        s.add(c)

        // Does not work
        //st.addToComponents(c)
    }
}
st.save(flush:true,failOnError:true)
这不会在数据库中创建名为product_components的表。这就是我所期望的。 当我尝试使用addTo时,该组件有一个与之关联的产品实例,然后该产品实例将更改为我尝试将其保存到的st产品实例

我希望这是有道理的

我发现它将组件域中的产品映射为产品域中的组件

  static mappedBy = {components joinTable: [name:'product_components',
                    column:'COMPONENTS_ID',
                    key: 'PRODUCT_ID']}
我现在假设在Product表中使用mapped by可以修复它

static MappedBy = [components : //do something here ]
找到了答案,请参见下文:

我必须在我的产品域中添加以下内容

  static mappedBy = {components joinTable: [name:'product_components',
                    column:'COMPONENTS_ID',
                    key: 'PRODUCT_ID']}

并将产品名称更改为my Components domain中的部分。

按照现在的设置方式,您的Components类只允许一个产品。因此,产品与组件之间存在一对多关系,这就是未创建联接表Product_组件的原因

您还试图将组件实例分配给多个产品:

// To the 'pro' Product
new Components(product: pro)

// To the 'st' Product
st.addToComponents(c)
但是您的Components域类只允许一个产品,这就是被引用产品被覆盖的原因

如果您希望Components类具有多个产品,而您编写的代码正试图实现这些产品,则必须将product类添加到静态hasMany block-on组件中:

然后可以执行以下操作:

def c = new Components().save(flush: true)
pro.addToComponents(c)
st.addToComponents(c)

另一方面,我建议将您的域名设为单数,即替代和组件,以遵循Grails的约定并使其更有意义。

您是否也可以包括您的Grails app/conf/DataSource.groovy?您可能会发现Grails.util.DomainBuilder简化了域类实例的创建