How to get CDI produced entitymanager in non EJB #Dependent subclass, throwing NPE? - jpa

The persistence API uses JTA managed transactions which is configured in persistence.xml.
EntitymanagerProducer.java
#PersistenceContext( unitName = "PRO" )
EntityManager proEm;
#pro
#Produces
public EntityManager createProEntityManager () {
return this.proEm;
}
The above produced EntityManager could be injected into any #Stateless bean with qualifier #Pro as below,
#Stateless
#Local( OutRepositoryBeanLocal.class )
#Remote( OutRepositoryRemote.class )
#LocalBean
#TransactionAttribute( TransactionAttributeType.MANDATORY )
public class OutRepositoryBean implements OutRepositoryBeanLocal, OutRepositoryRemote {
#Inject
#Pro
private EntityManager entityManager;
#Inject
OutRepository outRepository;
/**
*
*/
#PostConstruct
private void init () {
this.outRepository.setEntityManager( this.entityManager );
}
The above piece of code works seemlessly with no error. But while delegating the job to #Dependent subclasses problem arises,
OutRepository.java
#Dependent
public class OutRepository extends BaseService< Out, Long > {
public OutRepository() {
// TODO Auto-generated constructor stub
}
#Override
protected Class< Out > t () {
return Out.class;
}
public List< Out > getOuts ( Long proId, String Out) {
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder(); <= NPE
CriteriaQuery< Out > criteriaQuery = builder.createQuery( t() );
Root< Out > endPointConfig = criteriaQuery.from( t() );
criteriaQuery.select( endPoint );
TypedQuery< Out > query = this.entityManager.createQuery( criteriaQuery );
return query.getResultList();
}
Whereas the BaseService.java is an abstract class containing generic crud methods.
BaseService.java
#Dependent
public abstract class BaseService< T, I extends Serializable > implements BaseEntity< T, I > {
protected abstract Class< T > t ();
#PostConstruct
protected abstract void init ();
public PersistenceUnitUtil persistenceUnitUtil;
public EntityManager entityManager;
#TransactionAttribute( TransactionAttributeType.MANDATORY )
#Override
public T save ( T t ) {
this.entityManager.persist( t );
return t;
}
While outRepsitory.save() is called there is no problem in transaction everything works great. Yet while outRepository.getOuts(Long proId,String Out), Following exception occurs
[2/7/18 18:19:36:187 IST] 0000003d BusinessExcep E CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method "getOuts" on bean "BeanId(pro-ear#pro-web-0.0.1-SNAPSHOT.war#OutRepositoryBean, null)". Exception data: java.lang.NullPointerException
at org.apache.openjpa.persistence.meta.MetamodelImpl.populate(MetamodelImpl.java:321)
at org.apache.openjpa.persistence.meta.MetamodelImpl.instantiate(MetamodelImpl.java:255)
at org.apache.openjpa.persistence.meta.MetamodelImpl.find(MetamodelImpl.java:224)
at org.apache.openjpa.persistence.meta.MetamodelImpl.<init>(MetamodelImpl.java:89)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.getMetamodel(EntityManagerFactoryImpl.java:346)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.getCriteriaBuilder(EntityManagerFactoryImpl.java:333)
at org.apache.openjpa.persistence.EntityManagerImpl.getCriteriaBuilder(EntityManagerImpl.java:1649)
at org.apache.openjpa.persistence.EntityManagerImpl.getCriteriaBuilder(EntityManagerImpl.java:101)
at com.ibm.ws.jpa.management.JPAExEmInvocation.getCriteriaBuilder(JPAExEmInvocation.java:394)
at com.ibm.ws.jpa.management.JPAEntityManager.getCriteriaBuilder(JPAEntityManager.java:494)
at com.org.uck.pro.db.out.control.OutRepository.getOuts(OutRepository.java:68)
at com.org.uck.pro.db.out.control.OutRepositoryBean.getOuts(OutRepositoryBean.java:108)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at com.ibm.ejs.container.EJSContainer.invokeProceed(EJSContainer.java:6207)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:568)
at org.apache.webbeans.ejb.common.interceptor.OpenWebBeansEjbInterceptor.callInterceptorsAndDecorators(OpenWebBeansEjbInterceptor.java:528)
at org.apache.webbeans.ejb.common.interceptor.OpenWebBeansEjbInterceptor.callToOwbInterceptors(OpenWebBeansEjbInterceptor.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor(InterceptorProxy.java:227)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:548)
at org.apache.webbeans.ejb.WSEJBInterceptor.callToOwbInterceptors(WSEJBInterceptor.java:152)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor(InterceptorProxy.java:227)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:548)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.doAroundInvoke(InvocationContextImpl.java:229)
at com.ibm.ejs.container.EJSContainer.invoke(EJSContainer.java:6098)
at com.org.uck.pro.db.out.boundary.EJSLocal1SLOutRepositoryBean_03076fb6.getOuts(EJSLocal1SLOutRepositoryBean_03076fb6.java)
at com.org.uck.pro.ejb.outs.control.OutBean.getOuts(OutBean.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
NullPointerException on CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();, Tried calling the entitymanager using super.entitymanger still the same error persists.
--
Thanks.

There is no Inject annotation in BaseService
Should be like you have it done in OutRepositoryBean
#Inject #Pro
public EntityManager entityManager;

Related

#Inject - UserTransaction throws weld error

Error:
Exception 1 :
org.jboss.weld.exceptions.DefinitionException: WELD-001451: javax.transaction.UserTransaction cannot be injected into an enterprise bean with container-managed transactions: [BackedAnnotatedField] #Inject com.evry.integrator.snow.model.dao.impl.GenericDaoImpl.userTransaction
at com.evry.integrator.snow.model.dao.impl.GenericDaoImpl.userTransaction(GenericDaoImpl.java:0)
StackTrace
at org.jboss.weld.module.ejb.WeldEjbValidator.validateInjectionPointForDefinitionErrors(WeldEjbValidator.java:40)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDefinitionErrors(Validator.java:336)
Code:
public abstract class GenericDaoImpl<T, PK> implements GenericDao<T, PK> {
private static final Logger LOG = Logger.getLogger(GenericDaoImpl.class.getName());
#PersistenceContext(unitName = "IntegratorMasterdataDS")
protected EntityManager em;
#Inject
UserTransaction userTransaction
Scrutiny Class
#Stateless
public class Scrutiny {
private static final Logger log = Logger.getLogger(Scrutiny.class.getName());
public Scrutiny() {
System.out.println("Scrutiny");
}
#Inject
StatusDao statusDao;
public JobStatus insertNewRecord(JobName jName) {
log.info("insertNewRecord:" + jName);
try {
statusDao.beginUserTransaction(); <--- Here i want to begin
statusDao.create(js);
statusDao.flush();
statusDao.commitUserTransaction(); <--- Here i want to Commit
} catch (Exception e) {
log.warning("insertNewRecord:" + e);
}
Status Dao:
public interface StatusDao extends GenericDao<JobStatus, String> {
List<JobStatus> checkExistingRecordToday(JobName jName);
}
Job Status Dao:
#Stateless
public class JobStatusDaoImpl extends GenericDaoImpl<JobStatus, String> implements StatusDao {
private static final Logger LOG = Logger.getLogger(JobStatusDaoImpl.class.getName());
#Override
public List<JobStatus> checkExistingRecordToday(JobName jName) {
As of now whole process is handled by JTA but i want to commit Scrutiny class instantantly which suggest job has just started and at end want to update the same.
You should remove the UserTransaction injection from your DAO generic object and handle the transaction within Scrutiny bean, annotating it with TransactionManagement.
Your bean code should become this:
#Stateless
#TransactionManagement(value=TransactionManagementType.BEAN)
public class Scrutiny {
private static final Logger log = Logger.getLogger(Scrutiny.class.getName());
#Inject
private UserTransaction utx;
public Scrutiny() {
System.out.println("Scrutiny");
}
#Inject
StatusDao statusDao;
public JobStatus insertNewRecord(JobName jName) {
log.info("insertNewRecord:" + jName);
try {
utx.begin(); <--- Here i want to begin
statusDao.create(js);
utx.flush();
utxcommit(); <--- Here i want to Commit
} catch (Exception e) {
log.warning("insertNewRecord:" + e);
}
}
With these changes, your DAO should continue to work using container managed transactions, while your specific bean can control the transaction as desired.

How to use different EntityManager based on condition at runtime?

My congfiguration is like below:
The abstract class:
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
// other methods create(T), edit(T), ...
The Ejb that extends the abstract class (i have many others EJBs and about 12 different persistence units):
#Stateless
public class FilesDao extends AbstractFacade<Files> {
#PersistenceContext(unitName = "myfirstPU")
private EntityManager firstEm;
#PersistenceContext(unitName = "mysecondPU")
private EntityManager secondEm;
// i have more than two persistenceUnit ...
#Override
protected EntityManager getEntityManager() {
return firstEm; // or secondEm based on condition
}
public FilesDao() {
super(Files.class);
}
public Files findByFileref(String inFileRef) {
try {
Query q = firstEm.createNamedQuery("Files.findByFileref"); // or secondEm based on condition
q.setParameter("fileref", inFileRef);
Files file = (Files) q.getSingleResult();
return file;
} catch (NoResultException e) {
return null;
}
}
I want to use FilesDao like this :
#Stateless
#LocalBean
public class FileBusiness {
#EJB
FilesDao fileDao;
public void myMethod(){
if(condition1){
//use the FileDao with the EnityManager **firstEm**
}
else if(condition2){
//use the FileDao with the EnityManager **secondtEm**
}
...
}
Is there a way to achieve that ?
I read about using CDI with produces method.
CDI-Producers are not that hard, see the following example.
The following classes are CDI-Qualifier annotations, which are used to distinguish implementations.
#Retention(RetentionPolicy.RUNTIME)
#Target({ TYPE, METHOD, FIELD, PARAMETER, CONSTRUCTOR })
#Qualifier
public #interface MyfirstPUQualifier { }
#Retention(RetentionPolicy.RUNTIME)
#Target({ TYPE, METHOD, FIELD, PARAMETER, CONSTRUCTOR })
#Qualifier
public #interface MysecondPUQualifier { }
The following is a CDI-Bean which injects the different EntityManagers and implements producer methods, making the two EntityManagers available to CDI, distinguished via CDI-Qualifiers
#ApplicationScoped
class MYProducer {
#PersistenceContext(unitName = "myfirstPU")
private EntityManager firstEm;
#PersistenceContext(unitName = "mysecondPU")
private EntityManager secondEm;
#Produces
#RequestScoped
#MyfirstPUQualifier
public EntityManager produceMyfirstPU(){
return firstEm;
}
#Produces
#RequestScoped
#MysecondPUQualifier
public EntityManager produceMysecondPU(){
return secondEm;
}
}
The following shows a CDI-Bean injecting both EntityManagers. This could be extracted to an abstract base class, because maybe needed by other DAOs as well.
#Stateless
public class FileDao {
#Inject
#MyfirstPUQualifier
private EntityManager emFirst;
#Inject
#MysecondPUQualifier
private EntityManager emSecond;
public void myDaoMEthod(){
final EntityManager em = getEntityManager();
...
}
private EntityManager getEntityManager(){
if(condition1){
return emFirst;
}
else if(condition2){
return emSecond;
}
}
}
No can use the FileDao bean without taking care what EntityManager to use, because shouldn't be decided in this bean anyway
#Stateless
#LocalBean
public class FileBusiness {
#EJB
FilesDao fileDao;
public void myMethod(){
// FileDao will decide what entity manager to use
fileDao.doStruff();
}
}

ApplicationContext Exception in Test with #WebMvcTest

I Have an Spring Boot Application (1.5.10.RELEASE) which contains a main (SpringBootApplication) like this:
#SpringBootApplication
#Configuration
#EntityScan(basePackages = { "db.modell", "db.modell.base" })
#ComponentScan(basePackages = { "de.gui.test" })
public class SpringBootConsoleApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
}
and two REST controllers like the following:
#RestController
#RequestMapping("/as")
public class AController {
#Autowired
private ARepository aRepository;
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Collection<A>> getAs() {
return new ResponseEntity<>(orgtFarbeRepository.findAll(), HttpStatus.OK);
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<A> getA(#PathVariable long id) {
A a = ARepository.findOne(id);
if (party != null) {
return new ResponseEntity<>(ARepository.findOne(id), HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}
}
Furthermore I have a single test like this:
#RunWith(SpringRunner.class)
#WebMvcTest(AController.class)
public class AControllerTest {
#Autowired
private MockMvc mvc;
#MockBean
private ARepository ARepository;
#Test
public void firstTest() throws Exception {
A a = new aFarbe();
a.set....
when(ARepository.findAll()).thenReturn(Collections.singleton(a));
mvc.perform(
get("/as")
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
)
.andExpect(status().isOk());
}
}
The repositories look like this:
public interface ARepository extends CrudRepository<A, Long>
{
Collection<A> findAll();
}
public interface BRepository extends CrudRepository<B, Long>
{
Collection<B> findAll();
}
A and B them self are JPA annotated classes. The whole application contains access to a database..
Furthermore I have a Service like this:
#Service
public class XService {
private static final Logger LOGGER = LoggerFactory.getLogger(XService.class);
#Autowired
private ARepository aRepository;
#Autowired
private BRepository bRepository;
...
}
The XService is not used via #Autowire or so (Just need to remove that):
So I try to run the AControllerTest I get the following error:
java.lang.IllegalStateException: Failed to load ApplicationContext at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
.. .. at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'XService': Unsatisfied dependency
expressed through field 'BRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'BRepository' available: expected at least 1
bean which qualifies as autowire candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
.. .. at
org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 26 more Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'BRepository' available: expected at least 1
bean which qualifies as autowire candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 44 more
My assumption is that during the test more context is started than it should. The question is how can I prevent that? Which means only to start the context for the AControler and nothing more? I thought that based on the #WebMvcTest(AController.class) it should be limited already which looks like that it was not the case...
The referenced answer does not really answered my question but a in the context a hint gave me the solution. This means in consequence to add the following to my test:
so I have to add #OverrideAutoConfiguration(enabled=true):
#RunWith(SpringRunner.class)
#WebMvcTest(OrgtFarbenController.class)
#OverrideAutoConfiguration(enabled=true)
public class AControllerTest {
...
}

How to inject dynamic EntityManager into a Third Party Library

I have a library with some functionality that I want to reuse in other projects. My issue is that my service requires writing to the database. I would like for my library to use the datasource of the project that is inject my service.
Here is the minimal setup of my service
#Stateless
public class CustomService {
//to be added in producer
private EntityManager em;
private Principal principal;
//default constructor
public CustomService() {}
//custom constructor called in provider
public CustomService(Principal p, EntityManager e) {
principal = p;
em = e;
}
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
#Transactional
public CustomJPAObject createObject(...params...) {
//create JPA Object
em.persist(customObject);
em.flush();
return customObject;
}
}
I created a Custom Annotation for overriding the datasource
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE,ElementType.FIELD, ElementType.METHOD})
public #interface DynamicDS {
#Nonbinding String value() default "";
}
I also created a Singleton to be an EntityManager Producer
#Singleton
public class CustomEMProducer {
private Map<String, EntityManagerFactory> emfMap = new HashMap<>();
#Produces #Dependent #DynamicDS
public EntityManager produceEntityManager(InjectionPoint injectionPoint) {
String dataSourceName = null;
for(Annotation qualifier: injectionPoint.getQualifiers()) {
if(qualifier instanceof DynamicDS) {
DynamicDS dds = (DynamicDS) qualifier;
dataSourceName = dds.value();
break;
}
}
EntityManagerFactory emf = emfMap.get(dataSourceName);
if (emf == null) {
emf = Persistence.createEntityManagerFactory(dataSourceName);
emfMap.put(dataSourceName, emf);
}
return emf.createEntityManager();
}
#PostConstruct
public void cleanup() {
emfMap.entrySet().stream().forEach(entry -> entry.getValue().close());
}
}
Here is the code for my Service Producer
#Stateless
public class CustomServiceProvider {
#Inject private Principal principal;
#Produces #Dependent #DynamicDS
public BackgroundJobService getBackgroundJobService(InjectionPoint injectionPoint) throws EntityManagerNotCreatedException {
Annotation dsAnnotation = null;
for(Annotation qualifier: injectionPoint.getQualifiers()) {
if(qualifier instanceof BackgroundJobDS) {
dsAnnotation = qualifier;
break;
}
}
if (dsAnnotation != null) {
EntityManager em = CDI.current().select(EntityManager.class, dsAnnotation).get();
CustomService service = new CustomService(principal, em);
return service;
}
throw new EntityManagerNotCreatedException("Could not Produce CustomService");
}
}
The following is where I try to inject my new service
#Stateless
public class ProjectService {
#Inject #DynamicDS("project-ds") CustomerService service;
public CustomObject create(...params...) {
return service.createObject(...params...);
}
}
When I deploy my code and attempt to call the injected service I get the following error:
Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.checkTransactionNeeded(AbstractEntityManagerImpl.java:1171)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1332)
...
It looks like all of the different levels of providers are preventing the #Transactional on the CustomService.createObject() method call from propagating the transaction. Does anyone have insight into why this is or an alternate way of accomplishing my goal of injecting a dynamic EntityManager?
After much experimenting, I was unable to get dynamically generate an EntityManager through the above code. After much research, I gave up on trying to pass in the name from outside the 3rd part library. I would up creating the following interface:
public interface CustomEntityManager {
EntityManager getEntityManager();
}
This meant that inside the project that uses the 3rd party service I can do the create the following implementation to inject the EntityManager
public ProjectSpecificEntityManager implements CustomEntityManager {
#PersistenceContext(unitname = "project-ds")
private EntityManager em;
public EntityManager getEntityManager() {
return em;
}
}
I had to update my CustomService to the following
#Stateless
public class CustomService {
//Ignore warning about no bean eligible because it is intended
//that the project that uses this library will provide the
//implementation
#SuppressWarnings("cdi-ambiguous-dependency")
#Inject
CustomEntityManager cem;
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
#Transactional
public CustomJPAObject createObject(...params...) {
//create JPA Object
cem.getEntityManager().persist(customObject);
return customObject;
}
}

CONCURRENT_MAP_PUT failed at Address 192.168.11.208

I am trying to store data synchronously in cache and mongoDB. I am getting this exception
Exception in thread "main" com.hazelcast.core.HazelcastException: CONCURRENT_MAP_PUT failed at Address[192.168.11.208]:5702 because of an exception thrown at Address[192.168.11.208]:5701
at com.hazelcast.impl.BaseManager.rethrowException(BaseManager.java:188)
at com.hazelcast.impl.ConcurrentMapManager$MPut.txnalPut(ConcurrentMapManager.java:1902)
at com.hazelcast.impl.ConcurrentMapManager$MPut.txnalPut(ConcurrentMapManager.java:1818)
at com.hazelcast.impl.ConcurrentMapManager$MPut.put(ConcurrentMapManager.java:1682)
at com.hazelcast.impl.MProxyImpl$MProxyReal.put(MProxyImpl.java:632)
at com.hazelcast.impl.MProxyImpl$MProxyReal.put(MProxyImpl.java:606)
at com.hazelcast.impl.MProxyImpl.put(MProxyImpl.java:173)
at com.hazelcast.impl.MProxyImpl.put(MProxyImpl.java:124)
at mypackage.dao.EmployeeDAO.createNewEmployee(EmployeeDAO.java:52)
at mypackage.services.EmployeeManager.createNewEmployee(EmployeeManager.java:25)
at mypackage.controllers.EmployeeController.createNewEmployee(EmployeeController.java:24)
at mypackage.hazelcastspring.App.main(App.java:29)
Caused by: java.lang.NullPointerException
at mypackage.services.EmployeeMapstore.store(EmployeeMapstore.java:61)
at mypackage.services.EmployeeMapstore.store(EmployeeMapstore.java:1)
at com.hazelcast.impl.concurrentmap.MapStoreWrapper.store(MapStoreWrapper.java:114)
at com.hazelcast.impl.ConcurrentMapManager$PutOperationHandler$PutStorer.doMapStoreOperation(ConcurrentMapManager.java:3091)
at com.hazelcast.impl.ConcurrentMapManager$AbstractMapStoreOperation.run(ConcurrentMapManager.java:3795)
at com.hazelcast.impl.executor.ParallelExecutorService$ParallelExecutorImpl$ExecutionSegment.run(ParallelExecutorService.java:212)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at com.hazelcast.impl.ExecutorThreadFactory$1.run(ExecutorThreadFactory.java:38
I am having POJO class contains two String and i am using com.hazlecast.core.Mapstore library
Mainclass
public static void main(String[] args) {
CacheTesting testObj = new CacheTesting();
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
EmployeeController obj = (EmployeeController) context.getBean("employeeController");
obj.createNewEmployee();
testObj.cacheMembers();
testObj.clearCacheMembers();
testObj.cacheSize();
testObj.deleteCache(2);
testObj.getCacheMember(1);}
/////Dao class
public EmployeeDTO createNewEmployee() {
System.out.println("----Create new employee of DAO class called----");
getEmployeeDTO.setFirstName("Name");
getEmployeeDTO.setLastName("lastName");
System.out.println("DAO object: "+getEmployeeDTO);
getEmployeeMap().put(3,getEmployeeDTO);
return getEmployeeDTO;
}
////MapStore class
public class EmployeeMapstore implements MapStore<Integer, EmployeeDTO> {
#Autowired
EmployeeDTO getEmployeeDTO;
#Autowired
MongoOperations mongoOperations;
public synchronized void store(Integer key, EmployeeDTO geEmployeeDTO) {
System.out.println("----Store method of mapstore called----");
System.out.println("Before put method/Store method object: "+getEmployeeDTO);
mongoOperations.save(getEmployeeDTO);