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
Constraints provide Grails with a declarative DSL for defining validation rules, schema generation and CRUD generation meta data. For example, consider these constraints: class User { ... static constraints = { login size: 5.. 15, blank: false, unique: true password size: 5..
A domain class fulfills the M in the Model View Controller (MVC) pattern and represents a persistent entity that is mapped onto an underlying database table. In Grails a domain is a class that lives in the grails-app/domain directory.
The mapping static property configures how GORM maps the domain class to the database. See the section on the ORM DSL in the user guide for more information.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With