Entitymanager in additional data store

Hello,

I have a service in which I want to query a table from an additional datastore. I know to do it in Cuba but not in Jmix. Thanks.

Hi Tudor,

To work with EntityManager in additional datastore you will need to specify the store name and the transaction manager name.

Let’s say the store name is crm. Then if you have defned the additional datastore using Studio, it has created the CrmStoreConfiguration class. This class defines the crmTransactionManager bean among others (using the method with this name) - it’s the name of transaction manager for this store.

Use the store and transaction manager names in a Spring bean as follows:

@Component
public class CustomerBean {

    @Autowired
    private Metadata metadata;

    @PersistenceContext(unitName = "crm") // store name
    private EntityManager entityManager;

    @Transactional("crmTransactionManager") // transaction manager name
    public void createCustomerTransactionally() {
        Customer customer = metadata.create(Customer.class);
        customer.setName("def");
        entityManager.persist(customer);
    }
}

We’ll include this information in the docs soon.

Regards,
Konstantin

And if I want to use nativequery on “crm” datastore how do I specify it ? Example:

 EntityManager session = entityManagerFactory.createEntityManager();
        try {
            Boolean lResult = (Boolean) session.createNativeQuery("select dosomething()")
                    .getSingleResult();
        }
       catch (NoResultException e){
            System.out.println("Error:\n" + e.getMessage());
       }
        finally {
            if(session.isOpen()) session.close();
        }

Don’t use EntityManagerFactory, instead inject EntityManager as shown in the example above:

@PersistenceContext(unitName = "crm") // store name
private EntityManager entityManager;

@Transactional("crmTransactionManager") // transaction manager name
public void runQuery() {
    Boolean lResult = (Boolean) entityManager.createNativeQuery("select dosomething()")
                    .getSingleResult();
}
1 Like

Thanks, it works.
If you put it on the docs it will be great