modifying existing code to adapt nolock in jpa

1.5k Views Asked by At

What I want to achieve is, I would like to do a no lock query execution in select statement. But according to this answer it is impossible to achieve this with direct JPA implementation. I also understood from searches that nolock and READ_UNCOMMITTED are same. Is there any way to achieve this(no lock, READ_UNCOMMITTED) by modifying my below code. Or should I use the native query with specifying WITH(NOLOCK)

I had tried

entityManager.createQuery(query).setLockMode(LockModeType.NONE).getResultList();

but it also not solving my issue.

My references this, this , this, this

I am using the following code to get data from table. this code works fine without nolock.

String query = "FROM Employee WHERE empId=:empId AND empStatus='failed'";

to fetch data from db

public Object getListFromQuery(String query) throws Exception {
    Object resultObject = null;
    List<Object> queryResultList = null;
    EntityManager entityManager = null;
    try {
        entityManager = entityManagerFactory.createEntityManager();
        queryResultList = entityManager.createQuery(query).getResultList();
        resultObject = (Object) queryResultList;
    } catch (Exception ex) {
        LOGGER.error("Exception : DatabaseManager :executeQueryGetList  ",ex);
        throw ex;
    } finally {
        entityManager.close();
    }
    return resultObject;
}

Database configuration

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
        throws NamingException {
    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setDataSource(dataSource());
    factoryBean
            .setPackagesToScan(new String[] { "com.test.middleware.entity" });
    factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
    factoryBean.setJpaProperties(jpaProperties());
    factoryBean.setPersistenceUnitName("test_unit");
    return factoryBean;
}
0

There are 0 best solutions below