Spring Junit Hibernate @Transactional - 没有会话

时间:2017-07-06 13:42:56

标签: java spring hibernate session junit

我发现很多人都得到了这个例外,却找不到 为什么这发生在我身边:)。怎么会这样 在@Transactional方法中,何时 我指的是在同一个方法中从db加载的对象?

实体不应该分离,并且会话应该相同......但这不起作用。

我的对象中有一个懒惰的启动属性,并在尝试时 从中读取,Hibernate声明"没有会话",但是什么导致关闭呢?据我所知,hibernate session应该在@Transactional方法中存活,直到完成。

我尝试将@Transactional标记为@Test方法并且有效。

但是我想在一个测试方法中调用几个@Transactional方法,因为我必须保存实体并在单独的会话中加载它们。这是因为我使用@OrderBy并且仅当从DataBase加载对象时才有效。

这里测试类:

@Test
public void getOpenTest() {
    ...
    Advertisement closedAdvertisement = closeAdvertisement(initialAdvertisement.getId());
    ...
}

//this method inside same test class
@Transactional
private Advertisement closeAdvertisement(Long id){
    Advertisement advertisement = advertisementRepository.findOne(id);

    //*** CRASHES HERE ***
    //The method is @Transactional. Why session closed here?
    advertisement.getStatusChronology().get(0);

    ...
}

存储库

@Repository
public interface AdvertisementRepository  extends CrudRepository<Advertisement, Long> {
    //Simple request just to load entity 
    @Query("select ad  "
            + " from Advertisement ad")
    public List<Advertisement>getOpen();
}

实体

@Entity
@Table(name = "advertisement")
public class Advertisement {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO) 
    Long id;
    ...
    @OneToMany(mappedBy = "advertisement", cascade = CascadeType.ALL)
    @OrderBy("updated DESC")
    List<Status> statusChronology;
    ...
}

@Entity
@Table(name = "status")
public class Status {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO) 
    Long id;

    @ManyToOne
    @JoinColumn(name = "statusChronology")  
    private Advertisement advertisement;

    @NotNull
    @Column(name = "is_open")
    private Boolean isOpen;

    @NotNull
    @Column
    private LocalDateTime updated;  

    ...
}

异常

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: web.scraper.database.model.Advertisement.statusChronology, could not initialize proxy - no Session
    ...
    at web.scraper.database.repository.AdvertisementRepositoryTest.closeAdvertisement(AdvertisementRepositoryTest.java:80)
    at web.scraper.database.repository.AdvertisementRepositoryTest.getOpenTest(AdvertisementRepositoryTest.java:107)
    ...

1 个答案:

答案 0 :(得分:2)

show table extended like <your table name here> partition(<your partition spec here>); 不适用于私有方法。