Reputation: 8710
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
Upvotes: 5
Views: 3753
Reputation: 3567
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.
Upvotes: 5
Reputation: 4459
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
Upvotes: 6