tags:

views:

539

answers:

3

Hi!

I have a Grails application with a -simplified - domain class which looks like this:

class Capacity {

static constraints = {              
    month(blank:false, nullable:false)
    company(blank:false, nullable:false)
}


Date month    
Company company
String note
...
}

The pair month-company must be unique. (I.e. they should be primary key at the DB).

How can I define such a constraint?

Thanks a lot in advance

Luis

+2  A: 

Since you want this to be a composite primary key in the DB you will have to declare that mapping:

class Capacity implements Serializable {
    Date month    
    Company company
    String note
    ...

    static mapping = { 
        id composite:['month', 'company'] 
    } 
}

Which Produces the following table(MySQL):

CREATE
    TABLE capacity
    (
        MONTH DATETIME NOT NULL,
        company_id bigint NOT NULL,
        version bigint NOT NULL,
        note VARCHAR(255) NOT NULL,
        PRIMARY KEY (MONTH, company_id),
        INDEX FKFBF514BA69595C7A (company_id)
    )
    ENGINE=MyISAM DEFAULT CHARSET=latin1
Colin Harrington
thanks! This is exactly what I was looking for
Luixv
Does this still enforce the uniqueness during `validate()`? If not, I think a combination of this answer and Dave's are needed. Otherwise you'll end up getting SQL constraint exceptions instead of Grails validation errors.
Rob Hruska
+3  A: 

It should be something like:

static constraints = {              
    month(blank:false, nullable:false, unique:'company')
    company(blank:false, nullable:false)
}

Take a look at http://grails.org/doc/latest/ref/Constraints/unique.html.

Dave
A: 

Dave's answer is the right way and the Grails way of doing it.

VijayKumar
Upvoting Dave's answer is more appropriate than adding an answer of your own agreeing with him. If you haven't already, you can click the "up" arrow next to the answer to vote your approval. If you need to expand on his answer you can add a comment to his answer once you earn 50 rep.
Rob Hruska