我有以下服务类使用EntityManager
query()方法返回一个int。
public class QueryService {
@PersistenceUnit(unitName = "SpringHibernateJpaPersistenceProvider")
private EntityManagerFactory emf;
public int getCount(User user) {
EntityManager em = emf.createEntityManager();
int count;
Query qry = em.createQuery(
"select count(*) from User where managerId=? AND address=?");
qry.setParameter(1, user.getManagerId());
qry.setParameter(2, user.getAddress());
try {
count = ((Long) qry.getSingleResult()).intValue();
} catch (NoResultException nre) {
count = 0;
}
return count;
}
}
但是emf
返回null并且无法运行我的查询。我在EntityManagerFactory
方法上使用@Controller
完全相同的方法,这可以正常使用。也许我对EMF的工作原理还不够了解,有没有人有任何想法?
我的包结构
src
com.mysite.controllers
com.mysite.repositories
com.mysite.services
-QueryService.java
更新:我正在使用Java Config进行项目设置(无.xml) - 包括我的EMF配置
@Autowired
private Environment environment;
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.mysite" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setPersistenceProvider(vendorAdapter.getPersistenceProvider());
em.setPersistenceUnitName("SpringHibernateJpaPersistenceProvider");
em.setJpaProperties(additionalProperties());
return em;
}
答案 0 :(得分:0)
配置您的JPA Provider(使用persistence.xml
,hibernate.cfg.xml
或spring配置或注释)和Spring。
如果您已配置JPA和Spring,是否可以将这些文件添加到您的问题中,以便我们查看内容?