为什么Hibernate在concat字符串时更新数据库?

时间:2014-07-25 14:27:53

标签: hibernate spring-mvc

在db中我有一个包含Services和SubServices的表。

我需要创建一个函数来创建一个列表,用于这样的格式:

  
      
  • 服务1   
        
    • service 1.a
    •   
    • service 1.b
    •   
  •   
  • 服务2
  •   
  • 服务3   
        
    • service 3.a
    •   
  •   

我做了下面的功能,但我不明白为什么,这会更新数据库 添加& NBSP;&安培; NBSP;&安培; NBSP;&安培; NBSP;&安培; NBSP;&安培; nbsp;

我从不打电话给session.update。

由于

@SuppressWarnings("unchecked")
    @Override
    public List<Service> getFormattedServices() 
    {


        //lista main_services
        List<Service> main_services = getMainServices();

        List<Service> result = new ArrayList();

        Iterator<Service> iterator = main_services.iterator();
        while (iterator.hasNext())
        {
            Service tmp = iterator.next();

            //add the main service
            result.add(tmp);

            //scan of subservices
            Iterator<Service>iterator_s = tmp.getChildren().iterator();
            while (iterator_s.hasNext())
            {
                Service tmp2 = iterator_s.next();

                /*
                **********
                * why this line updates the row in DB ???
                *
                */
                tmp2.setTitolo("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".concat(tmp2.getTitolo()));

                //add the subservice
                result.add(tmp2);

                tmp2 = null;
            }
            iterator_s = null;

            tmp = null;
        }
        iterator = null;

        return result;
    }

2 个答案:

答案 0 :(得分:2)

因为您的对象状态为persistent。因此,将检测到任何更改并与db同步。如果你在事务中执行此操作,Hibernate将在关闭事务之前进行同步(不是针对它所命中的任何单个更改),否则它会针对每个对象属性更改进行命中。

Persistance:
* A persistance instance has a representation in database and an identifier value. 
It might have been just saved or loaded. It will be associated with a hibernate 
session.
* Hibernate will detect any changes made to an object in persistent state and 
synchronize the state 
with the database when the unit of work completes.

答案 1 :(得分:1)

您从Hibernate查询和会话方法获得的是附加实体。您对此类附加实体所做的任何修改都会透明地保存到数据库中,而无需调用任何方法。这是Hibernate的一个基本功能,你必须要注意。这非常有帮助。

由于您的方法在实体仍然附加时修改了实体(即,当用于获取它们的会话仍然打开时),显然,数据库已被修改。

您不应该修改实体只是为了在它之前显示一些空格。用于显示实体的代码不应修改实体。如果你坚持这个错误的方向,那么至少在修改它们之前从会话中分离实体,使用session.evict()

编辑:要显示您的服务列表,您只需要两个循环:

for (Service mainService : mainServices) {
    out.println(mainService.getTitle();
    for (Service subService: mainService.getChildren()) {
        out.println("&nbsp;&npsb;" + subService.getTitle());
    }
}

当然,这应该是你观点的一部分。假设您正在使用JSP,那就像

一样简单
<ul>
<c:forEach var="mainService" items="${mainServices}">
    <li>
        <c:out value="${mainService.title}"/>
        <ul>
            <c:forEach var="subService" items="${mainService.children}">
            <li><c:out value="${subService.title}"/></li>
        </ul>
    </li>
</c:forEach>
</ul>