Setting default maxLength for Grails GORM Strings?

2019-06-22 13:23发布

问题:

I know you can set default constraints via the grails.gorm.default.constraints config property by name by:

grails.gorm.default.constraints = {
    '*'(nullable:true)
}

but is there a way to set it by type? I want to default all my strings to default to maxSize:2000 (primarily to force the default db mapping to not be to varchar(255))

回答1:

I don't think there's any way to do this easily in Config.groovy. You can create a custom dialect for hibernate without too much trouble though. For example (using the Postgres dialect):

 package mypackage;

 import org.hibernate.dialect.PostgreSQLDialect;
 import java.sql.Types;

 public MyPostgresDialect extends PostgresSQLDialect {
     public MyPostgresDialect() {
         super();
         registerColumnType(Types.VARCHAR, "text");
     }
 }

Then update DataSource.groovy to use the new dialect:

datasource {
    ...
    dialect = mypackage.MyPostgresDialect
}


回答2:

Just to provide an additional answer I received from a co-worker - which wasn't applicable in this case, but might help others...

if you can follow a naming convention in your properties, then you could do a:

'*_s': (maxSize:2000)

I personally don't like cross-tying prop names and datatypes - but wanted to include this as an approach (even though I like the dialect answer by ataylor more...)



标签: grails gorm