论坛首页 Java版 Hibernate

hibernate二级缓存复合组合主键cache无法正确识别问题

浏览 1055 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
时间:2006-11-25
正确配置hibernate二级缓存,单主键的基本类型对象缓存读写没有问题,但是复合主键却无法识别,主要原因是equals中无法正常执行,主要是由于hibernate增强类和实际类不能正常识别。
如下面的判断对象是否相等的代码


public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final Commodity other = (Commodity) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}


每次执行到代码
if (getClass() != obj.getClass())
,总是返回false,debug后发现

引用
"getClass()"= Class<T> (com.nhsoft.togo.model.Commodity) (id=109)
annotations= null
annotationType= null
cachedConstructor= null
declaredAnnotations= null
declaredConstructors= SoftReference<T> (id=195)
declaredFields= null
declaredMethods= SoftReference<T> (id=198)
declaredPublicFields= null
declaredPublicMethods= SoftReference<T> (id=199)
enumConstantDirectory= null
enumConstants= null
genericInfo= null
name= "com.nhsoft.togo.model.Commodity"
newInstanceCallerCache= null
publicConstructors= null
publicFields= null
publicMethods= null

"obj.getClass()"= Class<T> (com.nhsoft.togo.model.Commodity$$EnhancerByCGLIB$$8f09cc88) (id=111)
annotations= null
annotationType= null
cachedConstructor= Constructor<T> (id=206)
declaredAnnotations= null
declaredConstructors= SoftReference<T> (id=210)
declaredFields= null
declaredMethods= SoftReference<T> (id=211)
declaredPublicFields= null
declaredPublicMethods= null
enumConstantDirectory= null
enumConstants= null
genericInfo= null
name= "com.nhsoft.togo.model.Commodity$$EnhancerByCGLIB$$8f09cc88"
newInstanceCallerCache= null
publicConstructors= null
publicFields= null
publicMethods= null



上面的判断语句使用时,认为增强类同正常使用类识别为两种不同的类,这个问题应该怎么解决?
   
时间:2006-11-26
我的解决办法是这样的,修改hibernate 复合主键equals方法实现
原来使用eclipse 3.2自动生成的equals方法:

	
if (getClass() != obj.getClass())  



现在改为:

	
if (!(obj instanceof CommodityCategory))



同时,发现使用hibernate Tool自动生成的复合主键equals实现代码也存在一个bug,hibernate tool生成的equals方法是这样的:
	public boolean equals(Object other) {
		if ((this == other))
			return true;
		if ((other == null))
			return false;
		if (!(other instanceof ShopHourId))
			return false;
		ShopHourId castOther = (ShopHourId) other;

		return ((this.getShop() == castOther.getShop()) || (this.getShop() != null
				&& castOther.getShop() != null && this.getShop().equals(
				castOther.getShop())))
				&& (this.getShopHourNum() == castOther.getShopHourNum());
	}


this.getShop() == castOther.getShop()) 应该使用 this.getShop().equals(castOther)替换

上述是我对一些理解,如果不正确,请指正。
   
0 请登录后投票
论坛首页 Java版 Hibernate

跳转论坛:
JavaEye推荐