@Entity
@Table(name = "TB_DICT")
public class Gender implements Serializable {
Long id; //字典主键
Long dictId; //字典类型编号:1表示性别
Long dictName; //字典类型名称
Long itemId; //项目编号 1:男 2:女
String itemName;//项目名称
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getDictId() {
return dictId;
}
public void setDictId(Long dictId) {
this.dictId = dictId;
}
public String getDictName() {
return dictName;
}
public void setDictName(String dictName) {
this.dictName = dictName;
}
public Long getItemId() {
return itemId;
}
public void setItemId(Long itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
在页面上用alert('${gender.itemName}')可正确显示当前记录的“性别”中文名称,可见关联关系是建立起来了。但在将某记录的性别从“男”修改为“女”,并保存(执行getSession().saveOrUpdate(user))时,发生如下错误:
org.springframework.orm.hibernate3.HibernateSystemException: identifier of an instance of accountant.entity.Gender was altered from 3 to 2;
从错误提示看,hibernate尝试更新gender的ID字段,而主键是不允许更新的,因此出错
这里有两个问题:
(1)建立关联只为了查询字典字段的中文名称,更新时只想更新TB_User的gender字段,而不是更新TB_DICT的值,这要如何设置?(是设置cascade参数吗?但CascadeType中似乎没有“NONE”一项)
(2)这里提示的“altered from 3 to 2”,3是“男”的id值,2是“女”的item_id值。既然已经设置了referencedColumnName = "itemId",即使要更新TB_DICT的值也应该更新的是item_Id字段,为什么实际会去更新id字段?
id dict_id dict_name item_id item_name
3 1 性别 1 男
4 1 性别 2 女