简体   繁体   中英

Grails unique constraint on year field only

Say, an Event domain class has eventDate property. There is a unique constraint on this eventDate, such that an event must be unique per year or per month. How to specify this in GORM?

class Event{
   String name
   Date eventDate

  static constraints{    
      eventDate() //----->unique per year or say month
  }

}

You can't. You would need something like a function-based index that builds the index based on a calculation from the column's values. This is supported in Oracle and some other databases, but there's no standard syntax for it and no support in GORM.

Of course you can do this explicitly for the database you're using in a migration script, eg when using the database-migration plugin, but that would be done in the database and there wouldn't be anything in the domain class to indicate that it was being used. And if you use H2 to do integration tests, you would either not have this feature and risk getting different results in different environments, or would have to figure out the equivalent syntax there.

Another option is a small denormalization where you add a second column and compute its values in the domain class before inserts and updates, and build a regular index on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM