Hello everybody first one excuse me for my bad english,
I am using spring framework and is configured with annotations but exist a error
this is my WebAppInitializer class i using for dispatcherServlet
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {RootConfig.class};
}
//CofiguraciĆ³n especifica de clases
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
/**
* Mapeo de DispatcherSerbvlet
* #return
*/
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
this Rootconfig class for scan the spring components
#Configuration
#ComponentScan(basePackages = {"com.factory.soft.web"},
excludeFilters = {
#Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)})
public class RootConfig {}
And the last class WebConfig
#Configuration
#EnableWebMvc //Habilita SpringMVC
#ComponentScan("com.factory.soft")
public class WebConfig extends WebMvcConfigurerAdapter{
/**
* El resolvedor de vistas de jsp
* #return
*/
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
return resolver;
}
#Bean
public PersistenceAnnotationBeanPostProcessor paPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
/**
* Configure Static contentc handling
* #param configurer
*/
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}}
for the JPA coniguration
#Configuration
#EnableJpaRepositories(basePackages="com.factory.soft.repository")
public class JPAConfig {
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/db");
dataSource.setUsername("user");
dataSource.setPassword("password");
return null;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource());
emfb.setPersistenceUnitName("SOFTPU");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emfb.setJpaVendorAdapter(vendorAdapter);
emfb.setJpaProperties(additionalProperties());
emfb.setPackagesToScan("com.factory.soft.domain");
return emfb;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.MYSQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
return adapter;
}}
This is error track of netbeans
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'exceptionTranslation' defined in class path resource [com/factory/soft/data/JPAConfig.class]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/aop/Advice
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
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:198)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:220)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:618)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:467)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:530)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:847)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: org/aopalliance/aop/Advice
at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1572)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1540)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
... 32 more
Caused by: java.lang.ClassNotFoundException: org.aopalliance.aop.Advice
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1295)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1147)
... 36 more
It looks like you are in need of following Jar (java.lang.ClassNotFoundException: org.aopalliance.aop.Advice):
aopalliance-1.0.jar
Please download the above Jar from http://aopalliance.sourceforge.net/ and add to the lib folder of your web application. Alternatively you may add following dependency to your pom.xml if you are using maven:
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
Two issues,
1.add AOP related dependencies in POM
2.You're returning dataSource as null in JPAConfig class
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/db");
dataSource.setUsername("user");
dataSource.setPassword("password");
return null;
}
change the return value to dataSource
Related
I'm writing a very simplistic crm web app and I've got a problem with autowiring hibernate sessionFactory bean in one of my DAO classes. I've been searching internet for couple days now and I'm quite confused, cause my config seems to mirror those that are said to be working on the net. In this project I don't use xml's.
web servlet config class
public class WebServletConfig implements WebApplicationInitializer
{
#Override
public void onStartup(ServletContext servletContext) throws ServletException
{
AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
webContext.register(SpringConfig.class);
webContext.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(webContext));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
spring config class
#Configuration
#EnableWebMvc
#ComponentScan("com.crmproject")
public class SpringConfig implements WebMvcConfigurer
{
#Bean
public ViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource()
{
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("resources/messages");
return messageSource;
}
public void configureDefaultSevletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
hibernate config file
#Configuration
public class HibernateConfig
{
#Bean
public LocalSessionFactoryBean sessionFactory()
{
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("com.crmproject.entity");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource()
{
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC");
dataSource.setUsername("hbstudent");
dataSource.setPassword("hbstudent");
return dataSource;
}
private final Properties hibernateProperties()
{
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
return hibernateProperties;
}
}
And I'm trying to autowire sessionFactory in this DAO class, but when I call testMethod to see if sessionFactory have been injected, it throws NullPointerException.
#Repository
public class CustomerDAOImpl implements CustomerDAO
{
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public void testMethod()
{
System.out.println(sessionFactory.toString());
}
public CustomerDAOImpl()
{
System.out.println("in CustomerDAOImpl constructor");
}
public List<Customer> getCustomers()
{
return null;
}
public Integer saveCustomer(Customer customer)
{
return null;
}
public Customer getCustomer(Integer id)
{
return null;
}
public boolean updateCustomer(Integer id, Customer customer)
{
return false;
}
public boolean deleteCustomer(Integer id)
{
return false;
}
}
exception:
SEVERE: Servlet.service() for servlet [dispatcher] in context with
path [/crm2-project] threw exception [Request processing failed;
nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException at
com.crmproject.dao.CustomerDAOImpl.testMethod(CustomerDAOImpl.java:26)
at
com.crmproject.controller.CustomerController.listCustomers(CustomerController.java:31)
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:498) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:501)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Why isn't Spring injecting sessionFactory bean?
edit:
Adding controller code per request
#Controller
#RequestMapping("/customer")
public class CustomerController
{
#RequestMapping("/customerAddForm")
public String showAddCustomerForm(Model model)
{
model.addAttribute("customer", new Customer());
System.out.println("Inside showAddCustomerForm method");
return "customer-add-form";
}
#RequestMapping("/list")
public String listCustomers(Model model)
{
List<Customer> customers = new ArrayList<>();
new CustomerDAOImpl().testMethod();
model.addAllAttributes(customers);
return "list-customers";
}
#RequestMapping("/proccessAddForm")
public void proccessAddForm(#ModelAttribute("customer")Customer customer)
{
System.out.println("Inside proccessAddForm method, customer: " + customer.toString());
}
}
The problem was in my Controller class. I tried to create the CustomerDAOImpl object using "new CustomerDAOImpl().testMethod();". Spring obviously didn't like it. I changed it to
"#Autowired
CustomerDAOImpl customerDAOImpl;" and now it's working, NullPointerException is gone. What a dumb mistake but at the same time, great learning experience. Thanks for help!
NOTE: This may sound a duplicate but I have everything working from other threads
I am implementing my own dao classes with spring and I am not able to configure spring with hibernate properly or maybe something else is at fault.
I am using java based configuration but still getting error. Please have a look
Hibernate configuration:
#Configuration
#ComponentScan("com.caveatemptor")
#EnableJpaRepositories
#EnableTransactionManagement
public class SpringDataJPAConfiguration {
private Logger LOG = LoggerFactory.getLogger(SpringDataJPAConfiguration.class);
// #Bean(destroyMethod = "close")
// public BasicDataSource dataSource() {
// BasicDataSource basicDataSource = new BasicDataSource();
// basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
// basicDataSource.setUrl("jdbc:mysql://localhost/ce");
// basicDataSource.setUsername("root");
// basicDataSource.setPassword("root");
// basicDataSource.setInitialSize(1);
// basicDataSource.setMaxIdle(5);
// basicDataSource.setMaxOpenPreparedStatements(10);
// LOG.debug("+++++++++++++Datasource Configured");
// return basicDataSource;
// }
#Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource basicDatasource = new DriverManagerDataSource();
basicDatasource.setDriverClassName("com.mysql.jdbc.Driver");
basicDatasource.setUrl("jdbc:mysql://localhost/ce");
basicDatasource.setUsername("root");
basicDatasource.setPassword("root");
LOG.debug("+++++++++++++Datasource Configured");
return basicDatasource;
}
// #Bean
// public LocalContainerEntityManagerFactoryBean entityManager() {
// LocalContainerEntityManagerFactoryBean bean = new
// LocalContainerEntityManagerFactoryBean();
// bean.setDataSource(this.dataSource());
// bean.setLoadTimeWeaver(this.instrumentationLoadTimeWeaver());
// bean.setJpaProperties(this.jpaProperties());
// bean.setJpaVendorAdapter(this.vendorAdapter());
// bean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
// bean.setPackagesToScan("com.caveatemptor.core");
// bean.setPersistenceUnitName("jpwh");
// LOG.info("==================[Entity Manage Configured]==================");
// return bean;
// }
#Bean
public HibernateJpaVendorAdapter vendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
LOG.info("==================[Hibernate Jpa Vendor Configured]==================");
return adapter;
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setDataSource(this.dataSource());
jpaTransactionManager.setJpaProperties(this.jpaProperties());
// jpaTransactionManager.setEntityManagerFactory(this.entityManager().getObject());
return jpaTransactionManager;
}
#Bean
public InstrumentationLoadTimeWeaver instrumentationLoadTimeWeaver() {
return new InstrumentationLoadTimeWeaver();
}
public Properties jpaProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.format_sql", "true");
properties.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.DefaultNamingStrategy");
properties.setProperty("hibernate.order_by.default_null_ordering", "first");
LOG.info("==================[JPA Properties Configured]==================");
return properties;
}
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder bean = new LocalSessionFactoryBuilder(this.dataSource());
bean.setProperties(this.jpaProperties());
bean.addPackage("com.ceveatemptor");
LOG.info("Session Factory Configured+++++++++++++++++++");
return bean.buildSessionFactory();
}
}
This is a multimodule project using maven and therefore it is configured in web module as:
public class DispatcherServletInitConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SpringDataJPAConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebServletInitConfiguration.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Generic DAO Class:
public abstract class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {
#PersistenceContext
protected EntityManager em;
protected final Class<T> entityClass;
public GenericDAOImpl(Class<T> entityClass) {
this.entityClass = entityClass;
}
#Override
public T makePersistent(T entity) {
return em.merge(entity);
}
}
Since Most of threads mentioned that I need a #Transactional and here is the implementation
#Repository
#Transactional
#javax.transaction.Transactional
public class ItemDAOImpl extends GenericDAOImpl<Item, Long> implements ItemDAO {
public ItemDAOImpl() {
super(Item.class);
}
}
The Stacktrace:
Sep 02, 2017 11:30:22 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/portal] threw exception [Request processing failed; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'merge' call] with root cause
javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'merge' call
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:282)
at com.sun.proxy.$Proxy77.merge(Unknown Source)
at com.caveatemptor.core.dao.GenericDAOImpl.makePersistent(GenericDAOImpl.java:53)
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:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy79.makePersistent(Unknown Source)
at com.caveatemptor.web.controllers.ItemController.saveItem(ItemController.java:38)
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:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
This may be a typo or some major configuration error, I am not getting it.
Any Insight will be helpful.
EDIT 1: If you need any other information, Please let me know.
EDIT 2 I am open to all kind of suggestions even If it is to change entire configuration for hibernate/jpa module. But only Java/annotation based configuration
EDIT 3 I Solved it by migrating server from tomcat to wildfly and configured JNDI data source and now it is working fine.
I am using Spring 4.3 and JPA to my project. I used java configuration to configure Hibernate instead of XMl configuration. But when I am compiling below error message is received. Please direct me to resolve this problem.
Following is the stack trace
java.lang.IllegalStateException: could not find the type for bean named org.springframework.transaction.config.internalTransactionalEventListenerFactory
at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.getBeanClass(SpringBeanProcessor.java:456)
at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.processBean(SpringBeanProcessor.java:280)
at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.postProcessBeanFactory(SpringBeanProcessor.java:258)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:284)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:131)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.jboss.resteasy.plugins.spring.SpringContextLoaderListener.contextInitialized(SpringContextLoaderListener.java:48)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1284)
at org.apache.catalina.manager.HTMLManagerServlet.start(HTMLManagerServlet.java:666)
at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:217)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:136)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:616)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1533)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1489)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
JPA configuration class
`#Configuration
#EnableTransactionManagement
#PropertySource(value = { "classpath:application/core-application.properties" })
public class JPAConfiguration {
#Autowired
private Environment environment;
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan(new String[] { "com.dak.school.model" });
factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
factoryBean.setJpaProperties(jpaProperties());
return factoryBean;
}
/*
* Provider specific adapter.
*/
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
return hibernateJpaVendorAdapter;
}
/*
* Here you can specify any provider specific properties.
*/
private Properties jpaProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
// properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
#Bean
#Autowired
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(emf);
return txManager;
}
} `
Application properties file
> jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url =
> jdbc:mysql://localhost:3306/school_suit jdbc.username = root
> jdbc.password = admin123fg hibernate.dialect =
> org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=create-drop
> hibernate.show_sql = true hibernate.format_sql = true
Service implementation class
#Service
//#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
#Transactional
public class UserServiceImpl implements UserService{
#Autowired(required = false)
private UserDao userDao;
#Override
public void saveUser(final User user) {
userDao.create(user);
}
}
Dao implementation class
#Repository
public class UserDaoImpl extends DaoImpl<User,Long> implements UserDao {
}
Abstract Daoimpl class
public abstract class DaoImpl<T, PK extends Serializable> implements IDao<T, PK> {
/* Persistence Entity class type. */
protected Class<T> entityClass;
/* Entity manager to perform DAO operations. */
#PersistenceContext
protected EntityManager entityManager;
/**
* Constructor
*/
#SuppressWarnings("unchecked")
public DaoImpl() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
}
/*
* (non-Javadoc)
*
* #see com.fg.baking.core.dao.IDao#create(java.lang.Object)
*/
public T create(T t) {
this.entityManager.persist(t);
return t;
}
/*
* (non-Javadoc)
*
* #see com.fg.baking.core.dao.IDao#read(java.io.Serializable)
*/
public T read(PK id) {
return this.entityManager.find(entityClass, id);
}
/*
* (non-Javadoc)
*
* #see com.fg.baking.core.dao.IDao#update(java.lang.Object)
*/
public T update(T t) {
return this.entityManager.merge(t);
}
/*
* (non-Javadoc)
*
* #see com.fg.baking.core.dao.IDao#delete(java.lang.Object)
*/
public void delete(T t) {
t = this.entityManager.merge(t);
this.entityManager.remove(t);
}
/*
* (non-Javadoc)
*
* #see com.yummy.platform.spring.dao.BaseDao#findAll()
*/
#SuppressWarnings("unchecked")
public List<T> findAll() {
Query query = entityManager.createQuery("FROM " + entityClass.getName() + " c");
return (List<T>) query.getResultList();
}
}
Dependency details
<spring.version>4.3.0.RELEASE</spring.version>
<spring.security.version>4.2.2.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
<taglib.standard.version>1.1.2</taglib.standard.version>
<!--<servlet.api.version>3.0.1</servlet.api.version>-->
<servlet.api.version>3.1.0</servlet.api.version>
<servlet.api.jsp.version>2.3.1</servlet.api.jsp.version>
<resteasy.version>3.0.11.Final</resteasy.version>
<apache.commnos.beanutil.version>1.9.0</apache.commnos.beanutil.version>
<apache.commnos.codec.version>1.9</apache.commnos.codec.version>
<commons.collections.version>3.2.1</commons.collections.version>
<commons-digester.version>3.2</commons-digester.version>
<commons-logging.version>1.1.3</commons-logging.version>
<commons-dbcp.version>2.1.1</commons-dbcp.version>
<commons-lang.version>2.4</commons-lang.version>
<mysql.connector.version>6.0.5</mysql.connector.version>
<hibernate.core.version>5.2.9.Final</hibernate.core.version>
<javax.validation.version>1.1.0.Final</javax.validation.version>
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
I was getting a similar error while migrating an existing spring application(with XML configurations) to springboot:
APPLICATION FAILED TO START
Description:
The bean 'org.springframework.transaction.config.internalTransactionalEventListenerFactory' could not be registered. A bean with that name has already been defined and overriding is dis
abled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
And I fixed this by removing couple of duplicate "<tx:" configurations from my old xml.
Initially I had added that property spring.main.allow-bean-definition-overriding=true which will simply hide that error from console. But that is not fixing the underlying issue. Hence, removal of duplicate configuration fixed my issue.
Replace your transactionManager bean with this:
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setDataSource(dataSource());
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}
It seems to be an similar issue as https://issues.jboss.org/browse/RESTEASY-1241. I resolve my issue by upgrading RESTEasy from 3.0.10.Final to 3.0.19.Final.
I have Spring based application and I need to get Hibernate working. So I got inspired by this tutorial: A Guide to Hibernate with Spring 4 and I created java class(I want to configure Hibernate xml-less):
package com.mycompany.cmms.web.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class PersistanceJPAConfig {
#Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.vsb.cmms.domain" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em.getObject();
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/cmms");
dataSource.setUsername( "postgres" );
dataSource.setPassword( "xxx" );
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.setProperty("hibernate.query.factory_class", "org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory");
return properties;
}
}
But when I build and start my application i get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in com.vsb.cmms.web.config.PersistanceJPAConfig: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'entityManagerFactory' or 'persistenceUnitName' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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)
Caused by: java.lang.IllegalArgumentException: 'entityManagerFactory' or 'persistenceUnitName' is required
at org.springframework.orm.jpa.JpaTransactionManager.afterPropertiesSet(JpaTransactionManager.java:304)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
... 21 more
The error is saying that'entityManagerFactory' or 'persistenceUnitName' is required. But entity manager factory should be provided via entityManagerFactory().
When I debbuged thi bean I noticed that em.getObject() is returning null and possibly is causing the error although I do not know why is this happening. I am using Spring 4 and Hibernate 5.2.3.Final.
Your entityManagerFactory() method really shouldn't be calling #getObject() but instead you should write it as:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.vsb.cmms.domain" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
// just return the bean here
return em;
}
Spring handles that factory bean automatically giving your EntityManagerFactory instances.
Just found in the deeps of the internet...
If you want to make xml-less hibernate configuration with a chance easily control session(session for application or session for transaction), then you probably want to see this
Please note, the code as it is works perfectly until Hibernate 5.2 version
i create spring mvc + jpa project, I get an exception when I receive a bean my repository class. Configuration jpa is correctly, but i get error in this part of class controller.
#Controller
public class WebController {
private ApplicationContext context;
private PupilService pupilService;
private PupilRepository pupilRepository;
private void setUpField(){
if (context == null){
context = new AnnotationConfigApplicationContext(BeanClass.class);
}
if (pupilService == null){
pupilService = context.getBean(PupilServiceImpl.class);
}
System.out.println("1"); //print
if (pupilRepository == null){
System.out.println("2"); //print
pupilRepository = context.getBean(PupilRepository.class);
System.out.println("3"); // no
}
}
Exception
HTTP Status 500 - Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ua.korbo.persistence.repository.PupilRepository] is defined
StackTrace
**exception**
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ua.korbo.persistence.repository.PupilRepository] is defined
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
**root cause**
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ua.korbo.persistence.repository.PupilRepository] is defined
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371)
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:968)
com.ua.korbo.web.controller.WebController.setUpField(WebController.java:36)
com.ua.korbo.web.controller.WebController.printService(WebController.java:55)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
PersistenceContext
#Configuration
#EnableJpaRepositories(basePackages = {"persistence.repository"},
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager")
#EnableTransactionManagement
#PropertySource("classpath:app.properties")
public class PersistenceContext {
public PersistenceContext() {
}
/**
* The method that configures the datasource bean
* */
#Resource
private Environment env;
#Bean(destroyMethod = "close")
DataSource dataSource() {
HikariConfig dataSourceConfig = new HikariConfig();
dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));
return new HikariDataSource(dataSourceConfig);
}
/**
* The method that configures the entity manager factory
* */
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Environment env) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("entity");
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
jpaProperties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
/**
* The method that configures the transaction manager
* */
#Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
BeanClass
#Configuration
#Import({PersistenceContext.class})
public class BeanClass {
#Bean
public PupilService serviceDao(){
return new PupilServiceImpl();
}
}
PupilRepository
public interface PupilRepository extends CrudRepository<Pupil, Long> {
}
Please annotate interface PupilRepository with #Repository .
#Repository
public interface PupilRepository extends CrudRepository<Pupil, Long> {
}
And to access the same in controller you need to Autowire it . Something like
#Autowired
private PupilRepository pupilRepository;
Try and let me know ,if you face any problem.