【发布时间】:2013-11-04 10:22:31
【问题描述】:
我是 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 映射中,我使用 @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'
}
}
User.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
}
}
Role.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'´ 添加到每个域类中,可以解决问题,但这违背了继承的目的。
对不起,我的英语是第二语言
【问题讨论】:
-
我开始认为 grails hibernate 插件不应用纯 jpa MappedSuperclass 的相同概念,而是看起来它假定实体中的抽象类。扩展另一个实体与扩展 MappedSuperClass 的实体不同
标签: java hibernate grails groovy grails-orm