Error with #EnableAutoConfiguration and ##ComponentScan using Spring Boot + Spring Data - spring-data

I'm using the example Spring-Boot and Spring-Data for an exercise, but can not play the application, the following error occurs:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cepRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class br.com.boot.domain.Cep
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:687)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at br.com.boot.application.Application.main(Application.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Not an managed type: class br.com.boot.domain.Cep
at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:68)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:149)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:88)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:68)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:158)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 21 common frames omitted
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cepRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class br.com.boot.domain.Cep
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:687)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at br.com.boot.application.Application.main(Application.java:20)
... 6 more
Caused by: java.lang.IllegalArgumentException: Not an managed type: class br.com.boot.domain.Cep
at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:68)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:149)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:88)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:68)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:158)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 21 more
My class Cep
#Entity
public class Cep {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE)
private Long id;
#Column
private String cep;
public Cep(String cep) {
this.cep = cep;
validarCep(cep);
}
protected Cep(){
}
My Class CepRepository
public interface CepRepository extends CrudRepository<Cep, Long>{
List<Cep> findbyId(Long id);
}
My Class CepController
#RestController
#RequestMapping("/cep")
public class CepController {
#Autowired
private CepRepository repository;
#RequestMapping("/lista")
public String retornaListaCeps(){
Iterable<Cep> lista = repository.findAll();
return lista.toString();
}
}
My Class FactoryData
#Service
public class FabricaDados {
#Autowired
private CepRepository repository;
public void gravarCeps() {
repository.save(new Cep("14233-333"));
repository.save(new Cep("14530-000"));
repository.save(new Cep("14020-060"));
}
public Iterable<Cep> listarTodos() {
Iterable<Cep> ceps = repository.findAll();
return ceps;
}
and my Class Main
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages="br.com.boot")
#EnableJpaRepositories(basePackages="br.com.boot.repository")
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
FabricaDados fabrica = ctx.getBean(FabricaDados.class);
fabrica.gravarCeps();
System.out.println(fabrica.listarTodos());
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
Thanks.

Add an
#EntityScan(basePackageClasses=br.com.boot.domain.Cep.class)
to your Application.class
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-separate-entity-definitions-from-spring-configuration

You need to tell Hibernate where to find your #Entity classes. Guessing in your case this should be
#EntityScan(basePackageClasses=Cep.class)
...
public class Application {
...
}
Docs: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-using-the-default-package

Related

Spring #Autowired Failed

When I try to inject my service class using #Autowired, I faced some problem
My Rest Controller:
#RestController
#RequestMapping(value = "/SettlementType")
public class SettlementTypeController extends Abstract4EyeController<SettlementTypeAudit, SettlementType, Integer>{
#Autowired
#Qualifier("settlementTypeService")
SettlementTypeService service;
#Override
public Abstract4EyeService<SettlementTypeAudit, SettlementType, Integer> get4EyeService() {
return service;
}
}
My service:
#Service("settlementTypeService")
public class SettlementTypeService extends Abstract4EyeService<SettlementTypeAudit, SettlementType, Integer> implements IMasterFileUpload<SettlementTypeAudit, SettlementType, Integer>
{
#Autowired
SettlementTypeAuditRepository auditRepository;
//my implementations
}
Interface:
public interface IMasterFileUpload <AuditModel extends Base4Eye, MainModel extends ReadOnlyEntity, ID extends Serializable> {
public List<MainModel> getMainFromCollection(List<Map<String, String>> collection);
}
Abstract4EyeService:
public abstract class Abstract4EyeService<AuditModel extends Base4Eye, MainModel extends ReadOnlyEntity, ID extends Serializable> {
#JsonIgnore
public abstract MainModel getMainEntity(AuditModel auditModel);
}
My Stack Trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settlementTypeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: project.test.rms.service.SettlementTypeService project.test.rms.controller.SettlementTypeController.service; nested exception is java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at project.test.genie.config.BootConfig.main(BootConfig.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: project.test.rms.service.SettlementTypeService project.test.rms.controller.SettlementTypeController.service; nested exception is java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 16 common frames omitted
Caused by: java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)
at java.lang.reflect.Field.set(Unknown Source)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:557)
... 18 common frames omitted
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settlementTypeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: project.test.rms.service.SettlementTypeService project.test.rms.controller.SettlementTypeController.service; nested exception is java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at project.test.genie.config.BootConfig.main(BootConfig.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: project.test.rms.service.SettlementTypeService project.test.rms.controller.SettlementTypeController.service; nested exception is java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 16 more
Caused by: java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)
at java.lang.reflect.Field.set(Unknown Source)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:557)
... 18 more
I tried to Inject Settlementype Service, but it throws java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102 exception
The reason you are having problem autowiring SettlementTypeService is because Spring creates a proxy of that class internally. To work around this, you can create an interface to be implemented by SettlementTypeService and autowire with that interface in your controller.

EJB injection fails in custom ConstraintValidator on JPA persist

I have a problem with my JSF/JPA/Bean Validation app. Custom constraints annotating (JPA) entity fields don’t function correctly on JPA pre-persist although they work fine during JSF form validation
Environment:
NetBeans IDE 8.0.2 / GlassFish Server 4.1
JPA 2.1/EJB 3.2 /CDI 1.1/BeanValidation 1.1 /Hibernate Validator 5.0.0.Final
cdi-api.jar added to ejb/web projects as it seems it was missing.
Problem
My App contains a JSF 2.2 page whose backing/CDI bean (Register) contains references to fields of (JPA) entities on the server/EJB tier. The entities are annotated with constraint annotations, and during the form filling, the validation works fine. I think this is a fairly standard setup with a #Named(CDI) bean as the backing(controller) bean.
I have custom constraints (#UserName and #Email) that check username and email is unique. Again these are EJB validators, and inject an EJB service which is used to check if username/email is in the DB using JPQL. Again this works fine when the form itself is being validated, and the form action will not be called if either of these validations fails.
The problem starts when form validation is successful and the CDI bean makes the call to the ejb service to add the new entity. In the log I see;
Caused by: javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.
………………
Caused by: java.lang.NullPointerException
at com.nick.bookstore.validators.EmailValidator.isValid(EmailValidator.java:40)
(See attached logs)
And I am able to see that the injected LoginService in the EmailValidator is null.
EmailValidator uses LoginService:
#Inject
private LoginService loginService;
– so injection failed, and this causes a null pointer exception.
So when validation is invoked from the CDI bean – it works, when managed by JPA it fails.
I have seen a similar problem here but this does not answer my question.
I have written a JUnit test that invokes the EJB service to persist a entity(customer) directly and this confirms the error detailed above.
Any help on understanding what is happening here is appreciated.
BookStoreProcessingBean(ejb)
#Stateless
#LocalBean
public class BookStoreProcessingBean {
#PersistenceContext(unitName = "BookStorePU")
private EntityManager em;
….
public void addCustomer(Customer customer) {
em.persist(customer);
}
}
Entities; Person -> Extended by Customer
#Entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="Type")
public class Person implements Serializable {
public Person(Address homeAddress) {
this.homeAddress = homeAddress;
}
……..
#Basic
#Email
#NotNull(message = "Email field must have a value")
private String email;
……
}
#Entity
public class Customer extends Person implements Serializable {
#Embedded
private SecurityDetails securityDetails;
…….
}
Validators; #Email and #UserName
public class EmailValidator implements ConstraintValidator<Email, String> {
#Inject
private LoginService loginService;
#Override
public void initialize(Email constraintAnnotation) {
}
#Override
public boolean isValid(String email, ConstraintValidatorContext context) {
//First check for a valid pattern and then for existence in DB
........
return !loginService.emailAlreadyExists(email); //Failure here as loginService is null
}
public class UserNameValidator implements ConstraintValidator<UserName, String> {
#Inject
private LoginService loginService;
public UserNameValidator() {
}
#Override
public void initialize(UserName constraintAnnotation)
}
#Override
public boolean isValid(String userName, ConstraintValidatorContext context) {
boolean unAlreadyExists = loginService.userNameAlreadyExists(userName);
return !unAlreadyExists;
}
Log Output
Warning: A system exception occurred during an invocation on EJB BookStoreProcessingBean, method: public void com.nick.bookstore.ejb.BookStoreProcessingBean.addCustomer(com.nick.bookstore.entities.Customer)
Warning: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy305.addCustomer(Unknown Source)
at com.nick.bookstore.ejb.__EJB31_Generated__BookStoreProcessingBean__Intf____Bean__.addCustomer(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.jboss.weld.util.reflection.Reflections.invokeAndUnwrap(Reflections.java:414)
at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:127)
at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
at org.jboss.weld.bean.proxy.InjectionPointPropagatingEnterpriseTargetBeanInstance.invoke(InjectionPointPropagatingEnterpriseTargetBeanInstance.java:65)
at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
at com.nick.bookstore.ejb.BookStoreProcessingBean$Proxy$_$$_Weld$EnterpriseProxy$.addCustomer(Unknown Source)
at com.nick.bookstore.beans.Register.register(Register.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:284)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:133)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:85)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:478)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:424)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:388)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:340)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:158)
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:84)
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.prePersist(BeanValidationListener.java:62)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:748)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:691)
at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:229)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:4316)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4293)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4235)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
at com.nick.bookstore.ejb.BookStoreProcessingBean.addCustomer(BookStoreProcessingBean.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 60 more
Caused by: java.lang.NullPointerException
at com.nick.bookstore.validators.EmailValidator.isValid(EmailValidator.java:43)
at com.nick.bookstore.validators.EmailValidator.isValid(EmailValidator.java:22)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:281)
... 111 more

javax.ejb.EJBException java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName

I'm working on a JavaEE application with EJB.
I have an Entity called Medico which code is:
#Entity
public class Medico implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public Medico(String nome_medico, String morada_medico,
String esp, GregorianCalendar dnasc_medico, int tel_medico) { //construtor parametrico
super();
this.nome_medico = nome_medico;
this.morada_medico = morada_medico;
this.esp = esp;
this.dnasc_medico = dnasc_medico;
this.tel_medico = tel_medico;
}
#Id
#GeneratedValue
private int cod_medico; //bi
private String nome_medico;
private String morada_medico;
private String esp;
#Temporal(TemporalType.DATE)
private GregorianCalendar dnasc_medico;
private int tel_medico;
private ArrayList<GregorianCalendar> agenda_consultas;
private ArrayList<GregorianCalendar> agenda_atos;
private int total_atos;
private int total_presc;
public int getTotal_presc() {
return total_presc;
}
public void setTotal_presc(int total_presc) {
this.total_presc = total_presc;
}
public Medico(){ //construtor vazio
super();
}
public int getTotal_atos() {
return total_atos;
}
public void setTotal_atos(int total_atos) {
this.total_atos = total_atos;
}
public ArrayList<GregorianCalendar> getAgenda_consultas() {
return agenda_consultas;
}
public void setAgenda_consultas(ArrayList<GregorianCalendar> agenda_consultas) {
this.agenda_consultas = agenda_consultas;
}
public ArrayList<GregorianCalendar> getAgenda_atos() {
return agenda_atos;
}
public void setAgenda_atos(ArrayList<GregorianCalendar> agenda_atos) {
this.agenda_atos = agenda_atos;
}
public int getCod_medico() {
return cod_medico;
}
public void setCod_medico(int cod_medico) {
this.cod_medico = cod_medico;
}
public String getNome_medico() {
return nome_medico;
}
public void setNome_medico(String nome_medico) {
this.nome_medico = nome_medico;
}
public String getMorada_medico() {
return morada_medico;
}
public void setMorada_medico(String morada_medico) {
this.morada_medico = morada_medico;
}
public String getEsp() {
return esp;
}
public void setEsp(String esp) {
this.esp = esp;
}
public GregorianCalendar getDnasc_medico() {
return dnasc_medico;
}
public void setDnasc_medico(GregorianCalendar dnasc_medico) {
this.dnasc_medico = dnasc_medico;
}
public int getTel_medico() {
return tel_medico;
}
public void setTel_medico(int tel_medico) {
this.tel_medico = tel_medico;
}
#Override
public String toString() {
return "Medico [cod_medico=" + cod_medico + ", nome_medico="
+ nome_medico + ", morada_medico=" + morada_medico + ", esp="
+ esp + ", dnasc_medico=" + dnasc_medico + ", tel_medico="
+ tel_medico + "]";
}
}
Then I created a session bean implementation class:
#Stateless
public class HospitalManagement implements AdministradorSessionRemote,GestorSessionRemote {
/**
* Default constructor.
*/
#PersistenceContext(unitName="Hospital")
private EntityManager em;
public HospitalManagement() {
// TODO Auto-generated constructor stub
}
#Override
public String cria_medico(String nome_medico, String morada_medico,
String esp, GregorianCalendar dnasc_medico, int tel_medico) {
Medico md = new Medico (nome_medico, morada_medico, esp, dnasc_medico,tel_medico);
em.persist(md);
return "Medico "+Integer.toString(md.getCod_medico())+" criado!";
}
This class implements two interfaces, but the method above is only used in the following one:
#Remote
public interface GestorSessionRemote {
public String cria_medico(String nome_medico,String morada_medico,String esp,GregorianCalendar dnasc_medico, int tel_medico);
public String procura_nome_medico(String nome);
public String procura_cod_medico(int cod);
public String altera_morada_med(int cod, String morada);
public String altera_telemovel_med(int cod, int tel);
Then I created a client:
public class GestorClient {
public static void main(String[] args){
InitialContext ctx =new InitialContext();
GestorSessionRemote g=(GestorSessionRemote)ctx.lookup("java:global/HospitalEAR/Hospital/HospitalManagement!Sessions.GestorSessionRemote");
System.out.println(g.cria_medico(nomem, moradam, esp,cal,telm));
where the parameters of the method are obtained by scannig from the keyboard.
I've also created the following persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Hospital">
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
When I try to deploy the application, an error occurs. Here is the complete stacktrace:
Exception in thread "main" javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy236.cria_medico(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName Hospital
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:158)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:281)
at Sessions.HospitalManagement.cria_medico(HospitalManagement.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:55)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:205)
... 19 more
Could someone help me understand the reason why this is happening?
The obvious problem is that you didn't specify a jta-data-source and the transaction-type in your persistence.xml.
A jta-data-source is specified like this:
<persistence-unit name="Hospital">
<jta-data-source>jdbc/sample</jta-data-source>
</persistence-unit>
You have to create the JDBC resource in your Glassfish instance. To do this open the Glassfish Admin GUI under http://localhost:4848 and create a Connection Pool under Resources -> JDBC Connection Pools. Then create a JDBC resource under Resources -> JDBC Resources named jdbc/sample and make it reference the new connection pool.
Further, it looks like the server somehow thinks that you want to use transaction-type RESOURCE_LOCAL which requires that you specify an EntityManagerFactory to get an instance of the EntityManager.
JTA should be the default transaction-type in a Java EE environment but you may have to explicitly specifiy the transaction-type in the persistence.xml like this:
<persistence-unit name="Hospital" transaction-type="JTA">
See also:
persistence.xml different transaction-type attributes

Static method call from Eclipse Plugin: InjectionException

I have 2 plugin projects - generator.ui and generator.core.
The generator.ui depends on generator.core plugin for processes and data manipulation. However wherever there is an API call on generator.core (through static method invocation), I get an exception mentioned below:
org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: de/upb/crc901/serge/generator/Generator
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:63)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:243)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:224)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:167)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.executeItem(HandledContributionItem.java:850).........
Caused by: java.lang.ClassNotFoundException: de.upb.crc901.serge.generator.Generator cannot be found by de.upb.crc901.serge.ui_1.0.0.qualifier
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
Now this NoClassDefFoundError always comes for the class which contains static method for object creation as the design pattern followed is "Singleton".
Any help would be greatly appreciated.
Here is the code, From the UI plugin; the configuration hub class:
public class ConfigurationHub implements IConfigurationHub {
private IGenerator generator;
private static IConfigurationHub configurationHub;
/*
* Constructor private to make Singleton
*/
private ConfigurationHub() {
generator = GeneratorFactory.createGenerator(Generator.class);
}
public static synchronized IConfigurationHub getInstance() {
if(null == configurationHub) {
configurationHub = new ConfigurationHub();
}
return configurationHub;
}
}
The GeneratorFactory class is in Generator plugin:
public class GeneratorFactory {
private GeneratorFactory() {}
public static <T extends IGenerator> T createGenerator(Class<T> type) {
try {
return (T) type.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
Regards,
Sid

CommunicationException- failed to unmarshel Remote business interface looking up ejb3 in weblogic

My ejb 3 classes and remote interface are as follows :
package com.myeclipse.ejb3;
import java.io.Serializable;
public interface IMyBean extends Serializable
{
public void doSomething();
}
Remote interface:
package com.myeclipse.ejb3;
import javax.ejb.Remote;
#Remote
public interface MyBeanRemote extends IMyBean {
}
Stateless ejb:
package com.myeclipse.ejb3;
import javax.ejb.Stateless;
#Stateless(mappedName="ejb/MyBean")
public class MyBean implements MyBeanRemote
{
public void doSomething()
{
System.out.println("Hello world");
}
}
Project is successully deployed as a jar file in weblogic. I developed
a standalone client to call ejb. But this is failing. Kindly help.
I've included all the weblogic server libraries to connect to jndi and
remote business interface for complilation.
Client Code :
package Ejb3_Client;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class MyBeanClient {
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try {
Properties p = new Properties();
p.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
p.put("java.naming.provider.url", "t3://172.21.123.70:8001");
InitialContext ctx = new InitialContext(p);
MyBeanRemote bean = (MyBeanRemote) ctx.lookup("ejb/MyBean#com.myeclipse.ejb3.MyBeanRemote");
System.out.println("bean instance "+ bean);
bean.doSomething();
System.out.println("bean worked");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
But I am getting this exception:
javax.naming.CommunicationException [Root exception is
java.rmi.UnmarshalException: failed to unmarshal class
java.lang.Object; nested exception is:
java.lang.ClassNotFoundException: com.myeclipse.ejb3.MyBeanRemote]
at
weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:74)
at
weblogic.jndi.internal.WLContextImpl.translateException(WLContextImpl.java:439)
at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:395)
at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:380)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
Ejb3_Client.MyBeanClient.main(MyBeanClient.java:33) Caused by:
java.rmi.UnmarshalException: failed to unmarshal class
java.lang.Object; nested exception is:
java.lang.ClassNotFoundException: com.myeclipse.ejb3.MyBeanRemote at
weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:244) at
weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:348)
at
weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:259)
at weblogic.jndi.internal.ServerNamingNode_1030_WLStub.lookup(Unknown
Source) at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:392)
... 3 more Caused by: java.lang.ClassNotFoundException:
com.myeclipse.ejb3.MyBeanRemote at
java.net.URLClassLoader$1.run(URLClassLoader.java:200) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:188) at
java.lang.ClassLoader.loadClass(ClassLoader.java:307) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:252) at
weblogic.ejb.container.internal.RemoteBusinessIntfProxy.readObject(RemoteBusinessIntfProxy.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
at
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at
weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:197)
at
weblogic.rjvm.MsgAbbrevInputStream.readObject(MsgAbbrevInputStream.java:564)
at
weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:193)
at weblogic.rmi.internal.ObjectIO.readObject(ObjectIO.java:62) at
weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:240) ...
7 more
I searched a lot but din find the problem why it can't unmarshel remote interface.
the reason for above error mainly because in some java file which implements Serializable interface has been changed you can revert those files to previous version