I use spring-data-jpa
with spring-boot(v2.0.0.RELEASE)
, I just wrote a CRUD demo on MySQL, but an exception occurs during runtime, source code as f
In the service class please add a setter for entity manager by using the annoattion @PersistenceContext. To be specific, use
@PersistenceContext(type = PersistenceContextType.EXTENDED)
In this way, you can access lazy property.
Your test should be like this:
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class QuestionTesting {
@Test
public void test() {
}
}
You can add @Transactional
annotation to your test method to avoid this exception.
Method getOne
return the 'reference' (proxy) of the entity which properties can be lazy loaded. See it code - it uses getReference
method of EntityManager
. From it javadoc:
Get an instance, whose state may be lazily fetched.
In Spring the implementation of EntityManager
is org.hibernate.internal.SessionImpl - so without the Session the Spring can not get this method.
To have a session you can just create a transaction...