Spring Junit Hibernate @Transactional - no session
I find a lot of people get this exception but can't find why this happened to me :). How could this happen within a method @Transactional
when I refer to an object loaded from db inside the same method?
The entity shouldn't be detached and the session should be the same ... but that doesn't work.
I have a lazy triggered property on my object and when you try to read from it Hibernate states "no session", but what caused it to close? As I understand the hibernation session must be available inside the method @Transactional
before it ends.
I tried to mark the @Transactional
my method @Test
and it works.
But I would like to have multiple methods @Transactional
in one test method, because I have to save objects and load them in separate sessions. This is because I am using @OrderBy
and only works if the object is loaded from the database.
Here's the test class:
@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
@Repository
public interface AdvertisementRepository extends CrudRepository<Advertisement, Long> {
//Simple request just to load entity
@Query("select ad "
+ " from Advertisement ad")
public List<Advertisement>getOpen();
}
Objects
@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;
...
}
An exception
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)
...
source to share