java - hibernate : org. hibernate.LazyInitializationException:未能延迟初始化角色集合:没有 session 或 session 已关闭

标签 java spring hibernate session

我学会了 hibernate 。 但我被困在一个非常基本的观点上。

当出处如下

    Controller : data collection and ready to display 
    Service : Transaction processing
    Dao : access Database 

并以这种形式处理数据。


测试.java

@Entity
@Table ( name = "table_test" )
public class Test
{

    @Id
    @GeneratedValue ( strategy = GenerationType.AUTO )
    public long id;

    @OneToMany(fetch=FetchType.LAZY)
    @JoinColumn(name="test_id")
    @IndexColumn(name="orderBy")
    public List<TestItem> items;

}

测试项目.java

@Entity
@Table ( name = "table_item" )
public class TestItem
{

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="test_id", insertable=false, updatable=false)
    public Test parent;

    @Id
    @GeneratedValue ( strategy = GenerationType.AUTO )
    public long id;

}

TestDao.java

@Repository
public class TestDao
{

    @Autowired SessionFactory sessionFactory;

    protected Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    public Test get(long id){
        return (Test) getSession().createCriteria( Test.class )
                    .add( Restrictions.eq( "id", id ) ).uniqueResult();
    }
}

测试服务.java

@Service
@Transactional
public class TestService
{

    @Autowired
    TestDao testd;

    public Test get(long id){
        return testd.get( id );
    }

    public List<TestItem> getItems(Test test){
        List<TestItem> items = test.items;
        items.iterator();
        return items;
    }

}

测试 Controller .java

@Controller
@RequestMapping ( "/test" )
public class TestController extends BaseController
{
    @Autowired
    TestService testService;

    @RequestMapping ( "/{id}" )
    public String seriesList ( @PathVariable long id, Model model )
    {
        Test test = testService.get( id );

        //something...

        List<TestItem> lists = testService.getItems( test );

        for(TestItem item : lists)
        {
            Model.addAttribute(item.id);
        }

        return "index";
    }
}

异常

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.test.domain.Test.items, no session or session was closed
    org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
    org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
    org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)

如果我使用 Lazy 是出于什么原因。

这是因为它可能不会被列出的“Something”使用。

我知道如何解决一些问题。

1) 第一个解决方案是“已经列出”,但消除了懒惰的需要。

@Service
@Transactional
public class TestService
{

    @Autowired
    TestDao testd;

    public Test get(long id){
        Test test = testd.get( id );
        test.items.iterator();
        return test;
    }

    public List<TestItem> getItems(Test test){
        List<TestItem> items = test.items;
        items.iterator();
        return items;
    }

}

2) 第二个解决方案“通过内部事务处理”,但是这个解决方案使用,总是在事务中运行

@Controller
@RequestMapping ( "/test" )
public class TestController extends BaseController
{
    @Autowired
    TestService testService;

    @RequestMapping ( "/{id}" )
    public String seriesList ( @PathVariable long id, Model model )
    {
        return testService.view( id, model );
    }
}
@Service
@Transactional
public class TestService
{

    @Autowired
    TestDao testd;

    public Test get(long id){
        Test test = testd.get( id );
        return test;
    }

    public String view(long id, Model model){
        Test test = get( id );

        List<TestItem> lists = test.items;

        for(TestItem item : lists)
        {
            model.addAttribute( item.id );
        }

        return "index";
    }

}

似乎有几个问题。

所以,我只想在需要时才提出。

最佳答案

您需要了解 session 和 session 边界的概念。 Hibernate 出于性能原因与代理一起工作,除非需要,否则不会加载所有关联。对于 session 概念,您可以查看 here

如果您在 Spring 环境中(我认为您是),您可能需要检查 Open Session 过滤器。这将在请求的上下文中打开一个 session ,以便您可以访问所有层中的关联。您可能不想增加事务边界。

关于java - hibernate : org. hibernate.LazyInitializationException:未能延迟初始化角色集合:没有 session 或 session 已关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589180/

相关文章:

java - 用 Java 绘制 X-Y 图

java - JPA实体关系?

java - 在android中将时间戳转换为当前日期

java - 使用 Spring 以编程方式创建 SQL 语句

java - 在 Mongodb 中为嵌入式文档设置索引

java - Tomcat 已启动但未创建数据库表且本地主机为 :8080 shows "HTTP Status 404"

JavaFX 将属性保存到数据库

java - 将 mysql-connector.jar 添加到构建路径时出现错误的类文件 magic (cafebabe) 错误

java - 重新排序分配并添加围栏

java - @ManyToOne 与连接表的关系(nullable = false)