Grails 如何让GORM在地图上创建索引?
在我的Grails 2.3.7项目中,我有一个产品域类,如下所示:Grails 如何让GORM在地图上创建索引?,grails,gorm,Grails,Gorm,在我的Grails 2.3.7项目中,我有一个产品域类,如下所示: class Product { String code String description Map attributes static constraints = { code(unique: true) } static mapping = { code index: 'Code_Idx' attributes fetch:
class Product {
String code
String description
Map attributes
static constraints = {
code(unique: true)
}
static mapping = {
code index: 'Code_Idx'
attributes fetch: 'join'
cache true
id generator: 'hilo'
}
}
它转换为以下数据库:
create table product (id bigint not null, version bigint not null, code varchar(255) not null unique, description varchar(255) not null, primary key (id));
create table product_attributes (attributes bigint, attributes_idx varchar(255), attributes_elt varchar(255) not null);
create index Code_Idx on product (code);
数据库中有大约4000个产品,scaffold列表显示它们很好
除了,当我在代码上单击“排序”时(因为没有索引),我的服务器会执行以下操作:
explain select this_.id as id14_0_, this_.version as version14_0_, this_.code as code14_0_, this_.description as descript4_14_0_,
attributes2_.attributes as attributes14_2_, attributes2_.attributes_elt as attributes3_2_, attributes2_.attributes_idx as attributes2_2_
from product this_ left outer join product_attributes attributes2_
on this_.id=attributes2_.attributes
order by lower(this_.code) desc limit 90, 100
+----+-------------+--------------+------+---------------+------+---------+------+-------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------------+------+---------------+------+---------+------+-------+---------------------------------+
| 1 | SIMPLE | this_ | ALL | NULL | NULL | NULL | NULL | 4086 | Using temporary; Using filesort |
| 1 | SIMPLE | attributes2_ | ALL | NULL | NULL | NULL | NULL | 43975 | |
+----+-------------+--------------+------+---------------+------+---------+------+-------+---------------------------------+
显然,这需要时间。我可以手动添加索引:
ALTER TABLE `product_attributes` ADD INDEX(`attributes`);
然后它工作正常。我认为它首先应该是自动创建的-在这个没有索引的模式中没有什么意义-但是好的,我可以ping Gorm来做。我的问题是-我可以在域类中放入什么让Gorm添加此索引 Grails不会在示例中的“attributes”等列上自动创建索引。为了创建和管理这些索引,我强烈建议使用。这本书写得很好,并概述了如何使用它。谢谢你的建议,约书亚。但它看起来几乎和从应用程序代码运行“ALTER TABLE”一样不可移植——如果底层引擎以某种方式决定名称应该不同,那么它可能无法工作,更不用说它对NoSQL存储没有任何意义。我计划在许多不同的服务器上部署我的项目,其中一些服务器的配置可能与其他服务器不同。我认为,这种索引的制作应该由Gorm自己控制,至少要有一点提示。我想我需要确认这是一个遗漏,应该向Grails的人报告。你面临的问题与Grails本身面临的问题是一样的。使用什么样的SQL(或NoSQL)方言。项目(想到SpringBatch)以各种方言提供所有支持的ALTER/Setup脚本,并允许部署应用程序的人员决定要包括/应用哪些脚本,这种情况并不少见。我意识到这不是自动化的,但如果您想要完全自动化的东西(支持多种方言),那么您必须将其作为应用程序的一部分进行设计/实现。Josh,我理解优化可能不是小事,因此我非常感谢您的建议。看起来DBM即使在开发过程中也很有用。然而,这种情况应该足够简单,以便Gorm能够被很好地处理和移植。遗憾的是,我可以用一种默认属性类型删除一个简单的scaffold应用程序。我可以接受你的答复,但我认为这是一个丑陋的解决办法。我认为Grails应该在内部处理它。