Error occur when I make test code with roles! (LazyInitializationException when get member's roles!)
Reason
I made @OneToMany and @ManyToOne relationship to Member and MemberRole in order.
I set up @OneToMany fetch setting as 'LAZY' and it was the problem!
How to solve
I get help from chatGPT, my sweet cookie.
There are a couple of ways to fix this:
Eager Loading
You can change the fetching strategy of memberRoles from FetchType.LAZY to FetchType.EAGER in the Member entity. This means that memberRoles will always be loaded from the database when the Member entity is loaded. However, this can lead to performance issues if the memberRoles collection is large, or if you often load Member entities without needing the memberRoles collection.
Transactional Test
You can annotate your test method with @Transactional. This opens a new transaction for the test and keeps the Hibernate Session open for the entire test method. However, this might not be a good solution if you want to test behavior that involves transaction management, like rollback behavior.
Join Fetch
You can modify the method in your UserDetailsService implementation to fetch the memberRoles collection when it loads the Member entity. This can be done using a JPQL query with a JOIN FETCH clause, or by calling Hibernate.initialize(member.getMemberRoles()) after loading the Member entity. This solution allows you to keep the lazy fetching strategy and avoid unnecessary database access in other parts of your application.
Remember to choose the solution that best fits your use case. If you only encounter this problem in your tests and not in your actual application code, it might be best to solve it in the test setup, rather than changing your entity mapping or service code.
Problem
Reason
How to solve
I get help from chatGPT, my sweet cookie.