如何确保对多列(mm_book_id和mm_author_id)应用唯一约束?

时间:2011-03-14 12:24:03

标签: java hibernate grails gorm

我想知道是否有人想知道如何确保在联接表mm_author_books中,如何确保列(mm_book_idmm_author_id)是唯一的? 例如,我不希望该表包含book_idauthor_id的重复记录,如1,1和1,1。那么怎么做......

class Book {
    String title 
    static belongsTo = Author 
    static hasMany = [authors:Author]
    static mapping = { 
        authors joinTable:[name:"mm_author_books", key:'mm_book_id' ] 
    }
}

class Author { 
    String name
    static hasMany = [books:Book]
    static mapping = { 
        books joinTable:[name:"mm_author_books", key:'mm_author_id'] 
    }
}

我在“mm_author_books”域名中试过这个:

class mm_author_books {

 String book_agency_name    
 static constraints = {
    book_agency_name(unique:['mm_author_id','mm_book_id'])
    }
static belongsTo = [authors:Author, books:Book]

}

但收到以下错误:

  

引起:   org.codehaus.groovy.grails.validation.exceptions.ConstraintException:   抛出应用约束的异常   [独特]上课[班级   content_hub_admin.mm_author_books] for   值[[mm_author_id,mm_book_id]]:   约束的范围[唯一]   class [class]的属性[name]   content_hub_admin.mm_author_books]   必须是相同的有效属性名称   上课   content_hub_admin.mm_author_books $ _ clinit _closure1.doCall(mm_author_books.groovy:6)     在   content_hub_admin.mm_author_books $ _ clinit _closure1.doCall(mm_author_books.groovy)     ......还有28个

谢谢&此致

rsheyeah

1 个答案:

答案 0 :(得分:4)

类mm_author_books(更好的名称是作者书关系)没有属性mm_author_id和mm_book_id。试试这个:

class AuthorBookRelationship {

    String bookAgencyName

    static constraints = {
        bookAgencyName(unique:['author','book'])
    }

    static belongsTo = [author:Author, book:Book] //only one author and one book

    }
}