coolhwm
2011-11-19 13:50
浏览 234
已采纳

关于基于Hibernate留言板的疑惑,hibernate自动获取关联对象的问题

只有用户,和留言两个表,POJO如下:

 

public class Article {
    private Integer id;
    private String title;
    private String content;
    private User user;
                //省略setter,getter
}
public class User {
    private Integer id;
    private String username;
    private String password;
    private Set<Article> articles = new HashSet<Article>();
}

Article 的XML映射文件

 

<hibernate-mapping package="com.minibbs.domain">
    <class name="Article" table="T_ARTICLE">
        <cache usage="read-only"/>
        <id column="article_id" name="id">
            <generator class="sequence" />
        </id>
        <property name="title" column="title" type="string" length="20" not-null="true"/>
        <property name="content" column="content" type="text" />
        <many-to-one name="user" column="user_id" class="User" not-null="true" lazy="false" />
    </class>
</hibernate-mapping>

进入留言列表,读取所有留言

需要的信息有Article的title和content,以及User的username

 

<s:iterator value="#request.articles" id="a" status="s">
     <tr>
            <td><s:property value="#s.index"/></td>
            <td class="title"><s:property value="#a.title"/></td>
            <td class="content"><s:property value="#a.content"/> </td>
            <td class="username"><s:property value="#a.user.username"/></td>
    </tr>
</s:iterator>

查询语句

 

public List<Article> findAll() {
    return getHibernateTemplate().find("from Article");
}

此时,进入文章列表会产生多条SQL语句

 

 

Hibernate: 
    /* 
from
    Article */ select
        article0_.article_id as article1_0_,
        article0_.title as title0_,
        article0_.content as content0_,
        article0_.user_id as user4_0_ 
    from
        T_ARTICLE article0_
Hibernate: 
    /* load com.minibbs.domain.User */ select
        user0_.user_id as user1_1_0_,
        user0_.username as username1_0_,
        user0_.password as password1_0_ 
    from
        T_USER user0_ 
    where
        user0_.user_id=?
Hibernate: 
    /* load com.minibbs.domain.User */ select
        user0_.user_id as user1_1_0_,
        user0_.username as username1_0_,
        user0_.password as password1_0_ 
    from
        T_USER user0_ 
    where
        user0_.user_id=?
Hibernate: 
    /* load com.minibbs.domain.User */ select
        user0_.user_id as user1_1_0_,
        user0_.username as username1_0_,
        user0_.password as password1_0_ 
    from
        T_USER user0_ 
    where
        user0_.user_id=?
Hibernate: 
    /* load com.minibbs.domain.User */ select
        user0_.user_id as user1_1_0_,
        user0_.username as username1_0_,
        user0_.password as password1_0_ 
    from
        T_USER user0_ 
    where
        user0_.user_id=?

从User表中读取用户对象的SQL语句条数和发帖人的总个数有关一样。

 

请问这样是正常的么?我感觉用户的信息可以在一条SQL语句中同时可以拿出来?有必要么?

 

 

 

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题