我用hibernate查询数据库,在service层查询数据库后在service层设置了一下查询出来的pojo的属性,Hibernate居然给我更新到数据中了,代码如下:
DAO代码如下:
public City getCityById(String cityCode) throws DAOException {
try{
return (City)getHibernateTemplate().get(City.class, cityCode);
}catch(DataAccessException e) {
logger.error(e);
throw new DAOException("data access exception", e);
}
}
Service代码如下:
public City getCityById(String cityCode) throws ApplicationException {
try {
City city = cityDao.getCityById(cityCode);
city.setCityName("test1");
return city;
} catch (DAOException e) {
throw new ApplicationException("dao error", e);
}
}
执行完上面的service之后,Hibernate居然还执行了一条更新语句
update city set city_name='test1' where city_code='beijing';
问题补充
我发现若是不配置Spring的事务,就没有这个问题
<property name="transactionAttributes">
<props>
<prop key="create*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="get*">PROPAGATION_REQUIRED,-Exception</prop>
</props>
</property>
把上面get*那行去掉,就不会自动更新了。
但是这样的话就等于没有事务控制了,也是不行的。
DAO代码如下:
public City getCityById(String cityCode) throws DAOException {
try{
return (City)getHibernateTemplate().get(City.class, cityCode);
}catch(DataAccessException e) {
logger.error(e);
throw new DAOException("data access exception", e);
}
}
Service代码如下:
public City getCityById(String cityCode) throws ApplicationException {
try {
City city = cityDao.getCityById(cityCode);
city.setCityName("test1");
return city;
} catch (DAOException e) {
throw new ApplicationException("dao error", e);
}
}
执行完上面的service之后,Hibernate居然还执行了一条更新语句
update city set city_name='test1' where city_code='beijing';
问题补充
我发现若是不配置Spring的事务,就没有这个问题
<property name="transactionAttributes">
<props>
<prop key="create*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="get*">PROPAGATION_REQUIRED,-Exception</prop>
</props>
</property>
把上面get*那行去掉,就不会自动更新了。
但是这样的话就等于没有事务控制了,也是不行的。
2008年11月22日 10:13
5个答案 按时间排序 按投票排序
-
原因:您对已经持久的引用对象的值进行了修改
解决方案:<prop key="get*">的值设置为PROPAGATION_REQUIRED,readOnly2008年11月24日 12:09
-
引用<prop key="get*">PROPAGATION_REQUIRED,-Exception</prop>
实体对象,是不能直接操作的修改的; 要通过其他方式返回; 然后你可以处理然后,返回到服务层.
另外,可以修改下事物属性,看看. 也许get*没必要增加事务控制;2008年11月22日 10:16
-
city.setCityName("test1");
你在这个为持久化的对象赋值了,hibernate会将持久化的对象更新的。如果你将session中的这个对象清除,service执行完,就不会更行了