我已经为需要它的任何域类编写了一个解决方案,并且您不需要每次都 readapt。
class Catalog {
static mapping = {
id composite:['name', 'manufacturer']
columns {
name column:'cat_name'
manufacturer column:'manuf_id'
}
}
String name
Manufacturer manufacturer
}
class Order {
Catalog catalog
static mapping = {
}
static foreigners = [
catalog : [name : "catalog_name",
manufacturer: "catalog_manufacturer_name"]
]
}
这是我编写的 GORM 配置类,用于在域类中使用外国人。
package my.app.package
import java.util.Collection;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration;
import org.hibernate.MappingException;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
class MyCustomGrailsAnotationConfiguration extends GrailsAnnotationConfiguration{
private static final long serialVersionUID = 1;
private boolean _alreadyProcessed=false;
@SuppressWarnings("unchecked")
@Override
protected void secondPassCompile() throws MappingException {
super.secondPassCompile();
if(_alreadyProcessed){
return;
}
classes.values().each{rootClass ->
if(rootClass instanceof RootClass){
def domainClass= null
Boolean hasForeigners=false
try{
domainClass=Class.forName(rootClass.entityName,false,Thread.currentThread().getContextClassLoader())
hasForeigners = domainClass.metaClass.hasProperty(domainClass, 'foreigners')
}catch(Exception e){}
if(domainClass && hasForeigners){
rootClass?.table?.foreignKeyIterator?.each{fKey->
fKey?.columnIterator?.each{column->
domainClass.foreigners?.each{attrName,columns ->
columns.each{columnItmName,columnItmValue->
def exp=attrName+"_"
columnItmName.split("").each{exp+=(it==~/[A-Z]/) ? "_"+it:it}
exp=exp.toLowerCase()+".(id)\$"
//println "Expression:"+exp
if(column.name.matches(exp)){
//println "Match:"+column.name+" changing to "+columnItmValue
column.name=columnItmValue
}
}
}
}
}
}
}
}
_alreadyProcessed = true;
}
}
将 my.app.package.MyCustomGrailsAnotationConfiguration.groovy 类放在 src/groovy/my/app/package/MyCustomGrailsAnotationConfiguration.groovy 中,并在 DataSource.groovy 中注册:
dataSource {
pooled = true
driverClassName = ...
username = ...
password = ...
configClass = my.app.package.MyCustomGrailsAnotationConfiguration
}
我希望这对你有用。感谢@carlosmain 的帮助