2013-01-13 49 views
0

在我加入的新项目中,他们不断使用术语Hibernate和JPA。所以,我试图深入研究代码,并试图理解整个事情是如何工作的(我对Spring,JPA和Hibernate世界是新的)。我会尽力把这里的代码更好的理解: 1)有@Configuration类,他们有以下几点:Spring + Hibernate + jpa它是如何工作的?

@Resource 
private HibernateJpaVendorAdapter hibernateOracleJpaVendorAdapter; 

LocalContainerEntityManagerFactoryBean entityManager = 
new LocalContainerEntityManagerFactoryBean(); 
entityManager.setJpaVendorAdapter(hibernateOracleJpaVendorAdapter); 
entityManager.setPersistenceUnitName("abc"); 
      . 
      . 

因此,在这种配置类,我们正在返回EntityManagerFactory的。

2)然后有标记@Persistor一个persistor类,其中存储库的方法被调用(例如,用于保存操作):

blahblahRepository.save(blahblahEntity, abcdef); 

3)最后有一个存储库类,这是带注释的@Repository。再说,他们有这样的一段代码:

@PersistenceContext(unitName = "same as the name in persistence.xml") 
protected EntityManager entityManager; 

“保存”方法环绕JPA的persist方法:

getEntityManager().persist(entityObject); 

我的问题如下: 1)没有字关于Hibernate,而不是在hibernateJpaVendorAdapter中。我搜索了整个工作空间,并且只显示了3个hibernate字样,全部都在配置文件中。 2)从我拥有的任何知识中,应该使用EntityManagerFactory或EntityManager,但我们都在做?

回答

0

Hibernate是JPA规范的实现之一。由于您的项目选择Hibernate作为其JPA实现,因此它使用JPA API委托Hibernate。就像您使用JDBC API时一样,该API委托给特定的Oracle或PostgreSQL驱动程序。

EntityManagerFactory,如其名称所示,是EntityManager的工厂。我不明白为什么你不会同时使用这两个。 EntityManager是JPA API的主要接口,用于执行所有数据库操作(查找,持久化,合并,查询等)。在要求EntityManager创建EntityManager之前,必须先配置EntityManagerFactory。

+0

你没有这样做。春天为你做,并将它注入你的春豆。 –

+0

请原谅我的无知,但我们不是从EntityManagerFactory创建实体管理器。无论我到目前为止读过的博客/文档如何,它都表示:@PersistenceContext(unit =“abc”)EntityManager em; OR @PersistenceUnit EntityManagerFactory emf; EntityManagerFactory.createEntityManager()创建EntityManager。我的理解错了吗?如果没有,那么我们为什么要这样做? – user123

相关问题