identifier of an instance of was altered from to n

错误使用场景

public int receiveDogInfo(Dog dog) {
		dog.setIsMarked("1");
		dog.setSource("0");
		int result = 0;
		dog.setOldId(dog.getId());
		dog.setId(null);
		dog.setUpdateTime(new Date());
		dog.setCreateTime(new Date());
		result = DogDao.save(dog);
		return result;
	}

会报错如下

identifier of an instance of was altered from to null


1:bug出现原因,程序修改处于Persistent状态的实体的id,hibernate是不允许这样操作的,所以保存失败。

2:在这样的情况下,要修改id话,就需要new一个对象,将原来处于persistent状态的对象属性全部复制到新的对象上面,然后再保存。


正确用法应该如下

public int receiveDogInfo(Dog dog) {
                Dog dto= new Dog();
                dto = dog;
		dto.setIsMarked("1");
		dto.setSource("0");
		int result = 0;
		dto.setOldId(dto.getId());
		dto.setId(null);
		dto.setUpdateTime(new Date());
		dto.setCreateTime(new Date());
		result = DogDao.save(dto);
		return result;
	}



你可能感兴趣的:(identifier of an instance of was altered from to n)