我将 Spring 和 Hibernate 与自动生成的数据库一起使用(为此,我在 JPA 配置中将 "hibernate.hbm2ddl.auto"
设置为 "update"
属性)。
我还有一个注解为 @Configuration
的类,其中包含一个 @PostConstruct
方法,该方法在创建或更新数据库后在应用程序启动时调用。这是我用一些默认数据设置数据库的地方,如果它是空的(第一次启动)。
此刻我想执行一些自定义的 native SQL 查询。这些查询不会返回任何内容,它们只是配置内容(例如创建额外的索引或扩展)。
目前我一直在创建一个 SessionFactory
以创建一个新的 Hibernate Session
。我试过自动连接它,但它不起作用:
@Autowired
SessionFactory sessionFactory;
给我:Field sessionFactory in ... required a bean of type 'org.hibernate.SessionFactory' that could be not be found。
我知道我可能需要在别处配置它,但我不知道在哪里。 SO 上的几个答案使用 xml 配置文件,但我没有使用任何配置文件,所以我不能那样做。
Spring 是否可以通过适当的配置创建 SessionFactory
?
最佳答案
您甚至不需要访问 SessionFactory。请将您的脚本放入文件 src/main/resources/scripts/myscript.sql 中。然后,您可以使用 Spring 执行以下操作:
@Component
public class Startup {
@Autowired
private DataSource dataSource;
@PostConstruct
public void runNativeSql() {
ClassPathResource resource = new ClassPathResource("scripts/myscript.sql");
try(Connection connection = dataSource.getConnection()) {
ScriptUtils.executeSqlScript(connection, resource);
} catch (SQLException | ScriptException e) {
//LOG
}
}
}
关于java - 在 Spring 启动期间执行 native SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164943/