简体   繁体   English

lazy =“ false”在休眠4.3.x中不起作用

[英]lazy=“false” not working in hibernate 4.3.x

I am trying to test the functioning of lazy loading in hibernate with the following code. 我正在尝试使用以下代码在休眠状态下测试延迟加载的功能。

        Query query = session.createQuery("From Publishers as publisher where publisher.publisherName <= :name");
    query.setString("name", "penguin");
    Publishers publisher = (Publishers)query.iterate().next();
     Set<Books> booksByPublisher  = new HashSet<>();
    booksByPublisher = publisher.getBooks();
    session.close();
    System.out.println(publisher.getPublisherName());
   for(Books book : booksByPublisher) {
        System.out.println(book);
    }

mapping for publishers and books classes are as following, respectively: 出版商和书籍类的映射分别如下:

<class name="newapplication.domain.Publishers" table="PUBLISHERS" >
    <id name="publisherId" type="integer" column="PUBLISHER_ID"/>
    <property name="publisherName" type="string" column="PUBLISHER_NAME"/>
    <set name="books" table="BOOKS_PUBLISHERS" inverse="true" fetch="join" lazy="false">
        <key column="publisher"/>
        <many-to-many class="newapplication.domain.Books" column="book" />
    </set>
</class>



    <class name="newapplication.domain.Books" table="BOOKS" >
    <id name="bookId" type="integer" column="BOOK_ID">
        <generator class="sequence">
            <param name="sequence">BOOKIDSEQUENCE</param>
        </generator>
    </id>
    <property name="bookName" type="string" column="NAME"/>
    <many-to-one name="author" class="newapplication.domain.Authors" column="AUTHOR"/>
    <many-to-one name="cover" class="newapplication.domain.Covers" column="COVER"/>
    <set name="publishers" table="BOOKS_PUBLISHERS" lazy="false">
        <key column="BOOK"/>
        <many-to-many class="newapplication.domain.Publishers" column="PUBLISHER"/>

    </set>
</class>

Despite having set lazy="false" loading in the publisher class i get the following error. 尽管在发布者类中设置了lazy =“ false”加载,但我收到以下错误。

Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session

What is wrong here? 怎么了 Shouldn't the Set be loaded as soon as the database is hit for the publishers' object? 不应该在为发布者的对象命中数据库后立即加载Set吗?

Your many-to-one associations in Books are lazy; 您在“ Books中的多对一关联是懒惰的; that's where the exception comes from. 这就是异常的来源。

By default, all associations are lazy when using Hibernate native mappings, as opposed to JPA standard (when using JPA-style mappings) where to-one associations are eager by default. 默认情况下,与使用默认的一对一关联的JPA标准(使用JPA样式映射时)相反,使用Hibernate本机映射时所有关联都是惰性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM