gorm save方法导致选择查询触发

时间:2011-05-13 06:17:58

标签: hibernate grails gorm

我正在使用grails 1.3.7和zkoss,我的域模型如下所示,我在会话1中加载Person实体并通过UI对其进行更改。

在会话2中保存,我想保存实体。

所以从我的作曲家/控制器我调用一个服务方法(事务性),然后做person.save(),当我看到sql查询被触发时,我看到一个试图检索员工对象的查询。

之后会触发保存并抛出非唯一的异常情况 例外

  
    

org.hibernate.NonUniqueObjectException:具有相同标识符值的其他对象已与会话关联:[com.nthdimenzion.domain.Employee#2]

  

查询

Hibernate: select this_.id as id7_0_, this_.version as version7_0_, this_.emp_id as emp4_7_0_, this_.person_id as person5_7_0_ from person_role this_ where this_.class='com.nthdimenzion.domain.Employee' and this_.emp_id=?

class PersonService {
static transactional = true
def savePerson(Person person) {
    person = person.save();
}

}

class Person extends Party{

String firstName;
String middleName;  
static hasMany = [ personRoles : PersonRole ] -- lazy loaded

.... }

class PersonRole {
public static enum ROLETYPES{
    EMPLOYEE,AUTHOR
};
public boolean hasRoleType (ROLETYPES roleType){
    return false;
}
static transients = ['ROLETYPES']
static constraints = {
}
 }



class Employee extends PersonRole{
def empRoleType = [ROLETYPES.EMPLOYEE]
String empId
    static belongsTo = [person:Person]
 static transients = ['empRoleType', 'uid']
static constraints = {
    books(nullable:true)
    empId(unique:true)
}
static hasMany = [books:Book]
static mapping = { books cascade:"all" }
static belongsTo = [person:Person]
  ......
}

这种行为是否正确?

1 个答案:

答案 0 :(得分:1)

您必须在Employee映射中指定empId是主键 - 这可能是NonUniqueObjectException的唯一原因。

SQL查询必须来自empId字段的唯一约束。

为什么不使用Grails'/ Hibernate隐式id,您是否使用具有特定映射的旧数据库?

修改我不明白为什么唯一约束会导致NonUniqueObjectException - 你能不受约束地试试吗?

如果问题仍然存在,您必须从同一会话中保存对象两次 - 不知道它是如何发生的,可能是merge()来自早期会话的Employee

SQL查询是由唯一性约束引起的,这是正确的。