我是 Grails 和 GORM 的新手,但我在遗留 PostgreSQL 上有一个旧的 JPA2 (Hibernate) 应用程序要映射,但我无法让抽象类的继承工作,这是问题的一个例子,让我们使用这个表:
users (id serial, username varchar, password char(44), user_modified integer, last_modified timestamp);
roles (id serial, role varchar, description varchar, enabled boolean, user_modified integer, last_modified timestamp);
permissions (user_id integer, role_id integer, enabled boolean);
如您所见,这些表使用数字自动递增 id,但并非所有表都如此,在旧的 JPA 映射中,我使用 a@MappedSuperclass
来映射 ID 配置,例如 id 生成器和一些审计列:
@MappedSuperclass
public abstract class DefId {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
@NotNull
@Column(name = "user_modified")
protected Long userModified;
@Version
@Column(name = "last_modified")
@Source(SourceType.DB)
protected Date lastModified;
//getters and setters
}
这是我迄今为止在grails中尝试过的:
DefId.groovy:
abstract class DefId {
/*In the actual source this are protected fields
with public getters/setters removed for less code*/
Long id;
Long userModified;
Timestamp version;
static mapping = {
id generator: 'identity'
version 'last_modified'
userModified column: 'user_modified'
}
}
用户.groovy:
package maptest.domain
import maptest.model.DefId
class User extends DefId {
String username
String password
boolean enabled
static hasMany = [roles: Role];
static mapping = {
table name: "users", schema: "core"
roles joinTable: [name: "permissions", key: "user_id"]
}
static constraints = {
username blank: false, size: 2..20, matches: "^[A-Za-z]\\w+\$", unique: true
password blank: false, matches: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\$"
preferences unique: true
}
}
角色.groovy
package maptest.domain
import maptest.domain.DefId
class Role extends DefId{
String role
String description
boolean enabled
static hasMany = [users: User];
static belongsTo = [User];
static mapping = {
table name: "roles", schema: "core"
users joinTable: [name: "permissions", key: "role_id"]
}
static constraints = {
role blank: false, size: 2..20, matches: "^[A-Za-z]\\w+\$", unique: true
description size: 2..50
}
}
如果我将抽象类留在域结构中,我会遇到异常:org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: ERROR: relation "def_id" don't exists;
这是真的,但我并不想保留抽象类。
如果我更改包并将抽象类移动到 src/groovy 那么我得到:org.springframework.orm.hibernate4.HibernateSystemException: Unknown entity: mapetest.domain.User;
我还尝试将grails.gorm.default.mapping = { id generator: 'identity' }添加到 Config.groovy 并从超类中删除 id 字段,但这只会给我带来另一个错误:Error loading plugin manager: Identity property not found, but required in domain class [maptest.domain.Role]
有人知道吗?将id generator: 'identity' ' 添加到每个域类中,解决了它,但这违背了继承的目的。
对不起,我的英语是第二语言