spring-data-jpa 如何手动创建包含所有默认JPA属性的Spring JPA实体管理器

unftdfkk  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(166)

我需要手动创建一个实体管理器来支持多个数据源。(而不是像只有一个数据源时那样自动配置它),我实际上也需要手动设置所有的JPA属性,包括通常由Spring使用默认值设置的内容。这意味着我在application.yaml中指定的所有JPA参数以及Spring通常为其设置默认值的参数现在都必须手动加载和设置。
是否可以手动创建一个实体管理器,但让它自动使用application.yaml中的所有JPA属性?
这是我的代码

public LocalContainerEntityManagerFactoryBean entityManager(EntityManagerFactoryBuilder builder, DataSource secondDataSource) {
    Map<String, Object> props = new HashMap<>();

    // Is there a way to not do this one by one for all of the default JPA properties and what I specified in application.yaml?
    props.put("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
    // props.put("prop1", "propvalue1");
    // ...

    return builder.dataSource(secondDataSource).packages(MyEntity.class).properties(props).build();
}
p3rjfoxz

p3rjfoxz1#

假设您有一个名为myData的持久性单元

private EntityManager getEntityManager()    {
    EntityManagerFactory emf = null;

    try {
        emf = Persistence.createEntityManagerFactory("myData");
    } catch (Exception e)   {
        log.warn("An Error has occurred while creating persistence layer", e);
    }

    if (emf != null) {
        return emf.createEntityManager();
    } else {
        log.warn("An error has occurred while retrieving Entity Manager from Persistence factory");
        return null;
    }
}

并使用如下图

final EntityManager em = getEntityManager();
    assert em != null;
    EntityTransaction entityTransaction = em.getTransaction();

    try {
        entityTransaction.begin();
        userList.stream().forEach(user -> {
            em.merge(RestUtil.convertToDBUser(user));
        });
        entityTransaction.commit();
        log.info("Completed data persistence ");
    } catch (RuntimeException e)    {
        if (entityTransaction.isActive()) {
            entityTransaction.rollback();
        }
        log.warn("An error has occurred while committing JDBC transaction. ", e);
        throw e;
    } finally {
        em.close();
    }

相关问题