struts2+hibernate,有实体类User(用户)、Gender(性别),做字典字段的ManyToOne关联,如下:
用户类
Java代码
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name = "TB_User")
public class User{
Long id; //用户主键
String userName; //姓名
Gender gender; //性别
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
// 多对一定义
@ManyToOne(optional = true, fetch = FetchType.EAGER)
@JoinColumn(name = "gender", referencedColumnName = "itemId")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
}
性别类
Java代码
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Table;
@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;
}
}
页面:
Html代码
<script type="text/javascript">
$().ready(function(){
$("#gender").val('${gender.itemId}')//设置下拉框默认值
}
</script>
编号:
<input type="text" id="id" name="id" value="${id}"></input><br>
用户名:
<input type="text" id="id" name="userName" value="${userName}"><br>
性别:
<select id="gender" name="gender.id">
<option value="1">男</option>
<option value="2">女</option>
</select>
在页面上用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 女
不得其解,请大家帮忙 |