我尝试使用下面的代码初始化数据库
@Component
public class DataBase {
@Transactional
@PostConstruct
public void init() {
Query nativeQuery = entityManager.createNativeQuery("Native SQL Query");
nativeQuery.executeUpdate();
}
}
我得到了这个运行时异常
Caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1496) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_40]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_40]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_40]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_40]
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:380) ~[spring-orm-5.0.7.RELEASE.jar:5.0.7.RELEASE]
但是注入DataBase
并调用init
函数就可以了!
@Component
public class TestClass {
@Autowired
private DataBase dataBase;
@PostConstruct
public void test() {
dataBase.init();
}
}
为什么会这样!这是错误还是有某些原因?