我有一个配置了DataSource的Spring + Hibernate项目:
@Configuration
@Component
public class DataSourceConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource getDataSource() {
return DataSourceBuilder
.create()
.url("jdbc:firebirdsql://**********:3050/mydb?charSet=utf8")
.username("*****")
.password("*****")
.driverClassName("org.firebirdsql.jdbc.FBDriver")
.build();
}
}
EntityManagerFactoriesConfig:
@Configuration
public class EntityManagerFactoriesConfig {
@Autowired
private DataSource dataSource;
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean emf() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setPackagesToScan(
new String[]{"ekoncept"});
emf.setJpaVendorAdapter(
new HibernateJpaVendorAdapter());
return emf;
}
}
TransactionManagerConfig:
@EnableTransactionManagement
public class TransactionManagersConfig {
@Autowired
EntityManagerFactory emf;
@Autowired
private DataSource dataSource;
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager tm =
new JpaTransactionManager();
tm.setEntityManagerFactory(emf);
tm.setDataSource(dataSource);
return tm;
}
}
仅此而已,application.properties中没有数据库配置。
现在,我想访问EntityManager或EntityManagerFactory来执行SQL。我知道我应该在Spring中使用@Query注释,但是在这种情况下,我需要执行一个简单的SQL。我试图以多种方式做到这一点,最终在所有情况下我都获得EntityManager == null。如何获得对实体管理器或EntityManagerFactory的访问权限?