【问题标题】:Spring+hibernate+jpa how does it work?spring+hibernate+jpa是怎么工作的?
【发布时间】:2012-12-27 15:22:24
【问题描述】:

在我加入的新项目中,他们一直交替使用术语 Hibernate 和 JPA。因此,我尝试深入研究代码并尝试了解整个事情是如何工作的(我是 Spring、JPA 和 Hibernate 世界的新手)。我将尝试将代码放在这里以便更好地理解: 1) 有一个@Configuration 类,它们具有以下内容:

@Resource
private HibernateJpaVendorAdapter hibernateOracleJpaVendorAdapter;

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

所以,在这个配置类中,我们返回一个 EntityManagerFactory。

2)然后有一个标记为@Persistor的持久化类,其中调用了repository的方法(例如,用于保存操作):

  blahblahRepository.save(blahblahEntity, abcdef); 

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

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

“save”方法包裹了JPA的persist方法:

getEntityManager().persist(entityObject);

我的问题如下: 1) 除了 hibernateJpaVendorAdapter 之外,没有关于 Hibernate 的任何消息。我搜索了整个工作区,它只显示了 3 次出现 hibernate 一词,都在配置文件中。 2)从我所拥有的任何知识来看,应该使用 EntityManagerFactory 或 EntityManager 但我们两者都做?

【问题讨论】:

    标签: spring hibernate jpa


    【解决方案1】:

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

    EntityManagerFactory,顾名思义,是EntityManager 的工厂。我不明白你为什么不同时使用两者。 EntityManager 是 JPA API 的主接口,用于执行所有数据库操作(查找、持久化、合并、查询等)。 EntityManagerFactory 必须在要求它创建 EntityManager 之前进行配置。

    【讨论】:

    • 你没有这样做。 Spring 为您完成,并将其注入您的 Spring bean。
    • 原谅我的无知,但我们不是从 EntityManagerFactory 创建实体管理器。到目前为止,无论我读过什么博客/文档,它都说:@PersistenceContext(unit="abc") EntityManager em;或 @PersistenceUnit EntityManagerFactory 电动势; EntityManagerFactory.createEntityManager() 创建 EntityManager。我的理解错了吗?如果不是,那我们为什么要这样做?
    猜你喜欢
    • 2014-04-14
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    相关资源
    最近更新 更多