2

I need to create an Entity Manager manually to support having multiple datasources. I've realised that by creating it manually (instead of autowiring it as when you have only one single datasource), I actually do need to set all the JPA properties manually too, including what are usually set with default values by Spring. This means all the JPA parameters I specified in application.yaml and what Spring normally set default values for have now to be loaded and set manually.

Is there anyway to create an Entity Manager manually but have it automatically use all the JPA properties in application.yaml?

Here's my code

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();
}
His
  • 5,891
  • 15
  • 61
  • 82

1 Answers1

1

Let's say, you have a persistence-unit with the name 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;
    }
}

And use like below

    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();
    }
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105