I have this erro, when I tried to run my web app:
24-12-2015 13:42:38 ERROR:
org.springframework.web.context.ContextLoader - Context initialization
failed org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class
com.noi.vetrina.config.DataSourceConfig: Invocation of init method
failed; nested exception is java.lang.AbstractMethodError at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
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.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at
org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at
org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at
org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
at
org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750)
at
java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.lang.AbstractMethodError at
org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:278)
at
org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:802)
at
org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 25 more
This is my pom.xml:
<org.springframework-version>4.2.4.RELEASE</org.springframework-version>
<hibernate.version>5.0.5.Final</hibernate.version>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
<exclusions>
<exclusion>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
Is there into pom the problem??
EDIT this DataSourceConfig:
Configuration
#EnableJpaAuditing
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = { "com.noi.vetrina.repository" })
#Import({ DataSourceDevConfig.class, DataSourceProdConfig.class })
#PropertySource("classpath:/META-INF/persistence_mysql.properties")
public class DataSourceConfig {
private static final String DB_TYPE = "mysql_";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = DB_TYPE + "entitymanager.packages.to.scan";
#Resource
private Environment environment;
#Resource(name = "mysql")
private DataSource dataSource;
/**
* Configures the transaction manager.
*
* #return
* #throws ClassNotFoundException
*/
#Bean
#Primary
public JpaTransactionManager transactionManager() throws ClassNotFoundException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
/**
* Configures the entity manager factory.
*
* #return
* #throws ClassNotFoundException
*/
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
String pack = environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setPackagesToScan(pack);
entityManagerFactoryBean.setPersistenceUnitName("persistenceUnit");
Properties jpaProterties = new Properties();
jpaProterties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(DB_TYPE + PROPERTY_NAME_HIBERNATE_DIALECT));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(DB_TYPE + PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, environment.getRequiredProperty(DB_TYPE + PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(DB_TYPE + PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(DB_TYPE + PROPERTY_NAME_HIBERNATE_SHOW_SQL));
jpaProterties.put("hibernate.max_fetch_depth", 3);
jpaProterties.put("hibernate.jdbc.fetch_size", 50);
jpaProterties.put("hibernate.jdbc.batch_size", 20);
jpaProterties.put("hibernate.format_sql", true);
jpaProterties.put("hibernate.show_sql", false);
jpaProterties.put("org.hibernate.envers.audit_table_suffix", "_H");
jpaProterties.put("org.hibernate.envers.revision_field_name", "AUDIT_REVISION");
jpaProterties.put("org.hibernate.envers.revision_type_field_name", "ACTION_TYPE");
jpaProterties.put("org.hibernate.envers.audit_strategy", "org.hibernate.envers.strategy.ValidityAuditStrategy");
jpaProterties.put("org.hibernate.envers.audit_strategy_validity_end_rev_field_name", "AUDIT_REVISION_END");
jpaProterties.put("org.hibernate.envers.audit_strategy_validity_store_revend_timestamp", "True");
jpaProterties.put("org.hibernate.envers.audit_strategy_validity_revend_timestamp_field_name", "AUDIT_REVISION_END_TS");
entityManagerFactoryBean.setJpaProperties(jpaProterties);
return entityManagerFactoryBean;
}
#Bean
public AuditorAware<String> auditorProvider() {
return new AuditorAwareBean();
}
}
I solved it to downgrade the hibernate version... I'm using the 4.3.11.Final and it works...
Related
I'm writing a jpa repostory example and I'm getting a runtime exception of type UnsatisfiedDependencyException.
Here is my program:
#Configuration
#EnableJpaRepositories(basePackageClasses = { PersonRepository.class, ProfessionRepository.class})
#ComponentScan( basePackageClasses =MyService.class)
public class SpringDataJpa {
public static void main( String[] args ) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringDataJpa.class);
service myService = applicationContext.getBean(MyService.class);
}
}
The service interface:
public interface service {
void add( Person person );
List<Person> getListOfPersons();
}
The implementation that throw the exception:
#Service
public class MyService implements service {
#Autowired
PersonRepository personRepository;
#Override
public void add( Person person ){
System.out.println("saved");
}
#Override
public List<Person> getListOfPersons() {
return null;
}
}
The repositories:
#Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
}
#Repository
public interface ProfessionRepository extends JpaRepository<Profession, Integer> {
}
The exception i'm getting:
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'myService': Unsatisfied dependency
expressed through field 'personRepository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'personRepository': Post-processing of merged
bean definition failed; nested exception is
java.lang.NoClassDefFoundError: javax/persistence/SynchronizationType
As I checked this discussion, I added the proposed dependencies. My dependencies in the pom.xml file:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
How to solve this error?
My second question is: should we use #EnableJpaRepositories if we use Spring Boot?
a datasource and an entityManagerFactory beans were missing.
To solve my problem i added the followed code in my configuration class:
#Bean
public DataSource firstDataSource (){
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/ride_tracker?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
driverManagerDataSource.setUsername("root");
driverManagerDataSource.setPassword("password");
return driverManagerDataSource;
}
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory( DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("data");
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
You can try the following version, SynchronizationType is available since 2.1.
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
I have trouble to deploy my web app into a remote server.
It works completely fine when it's running on my machine - localhost:8080. (running fine at both cases at local machine where Tomcat started manually using .war file in webapps folder and, Eclipse - "run on server")
But I get 404 error when I try to connect after copying .war file into /webapps/ folder in remote server.
( I examed another sample.war file in the remote server, and it works fine. but not my .war file.)
I made .war file using command
$ mvn package
There is no web.xml file. and every configuration was made by java annotation.
I Used Tomcat9.
Also, I installed MySQL into Remote server. and managed everything in DB.
ExceptionHandlers.java
package com.rainbowtape.boards.config;
#ControllerAdvice
public class ExceptionHandlers {
#ExceptionHandler(NoHandlerFoundException.class)
public String handle(Exception ex) {
return "404";
}
}
MyServletInitializer.java
package com.rainbowtape.boards.config;
public class MyServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new SessionListener());
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { PersistenceConfig.class, WebSecurityConfig.class, };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
if(!done) throw new RuntimeException();
}
#Override
protected Filter[] getServletFilters() {
return new Filter[] {
new OpenEntityManagerInViewFilter()
};
}
}
NoHandlerFoundControllerAdvice.java
package com.rainbowtape.boards.config;
#ControllerAdvice
public class NoHandlerFoundControllerAdvice {
#ExceptionHandler(NoHandlerFoundException.class)
public String handle(Exception ex) {
return "redirect:/404";
}
}
PersistenceConfig.java
package com.rainbowtape.boards.config;
#Configuration
#EnableTransactionManagement
#ComponentScan({"com.rainbowtape.boards"})
#EnableJpaRepositories(basePackages = {"com.rainbowtape.boards.dao"})
#PropertySource({"classpath:persistence-mysql.properties"})
public class PersistenceConfig {
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
dataSource.setUsername(env.getRequiredProperty("jdbc.user"));
dataSource.setPassword(env.getRequiredProperty("jdbc.pass"));
return dataSource;
}
#Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
#Autowired
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("com.rainbowtape.boards.entity");
entityManagerFactoryBean.setJpaProperties(hibernateProperties());
return entityManagerFactoryBean;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
}
SecurityWebApplicationInitializer.java
package com.rainbowtape.boards.config;
#Configuration
#EnableWebMvc
#EnableSpringDataWebSupport
#ComponentScan(basePackages = "com.rainbowtape.boards")
public class SpringConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment env;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/images/**").addResourceLocations("file:///Users/rainbowtape/liffey-app/images/").setCachePeriod(0);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public SpringResourceTemplateResolver templateResolver() {
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setCacheable(false);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
springTemplateEngine.addTemplateResolver(templateResolver());
springTemplateEngine.addDialect(new SpringSecurityDialect());
return springTemplateEngine;
}
#Bean
public ThymeleafViewResolver viewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
viewResolver.setContentType("text/html;charset=UTF-8");
return viewResolver;
}
#Bean
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername(env.getRequiredProperty("gmail.username"));
mailSender.setPassword(env.getRequiredProperty("gmail.password"));
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
#Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setResolveLazily(false);
resolver.setMaxUploadSize(10000000);
return resolver;
}
}
WebSecurityConfig.java
package com.rainbowtape.boards.config;
#PropertySource({"classpath:maildata.properties"})
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger log = LoggerFactory.getLogger(WebSecurityConfig.class);
#Autowired
private UserService userService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
http.addFilterBefore(filter,CsrfFilter.class);
http
.csrf().disable() // https://stackoverflow.com/questions/28716632/spring-boot-request-method-post-not-supported
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/images/**").permitAll()
.antMatchers("/registerForm").permitAll()
.antMatchers("/forgotPassword/**").permitAll()
.antMatchers("/api/school/**").permitAll()
.antMatchers("/school/**").permitAll()
.antMatchers("/","/403","/register","/login","/loginError","/dbError","/404","/error","/validateLogin","/consulting","/test").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER","ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/validateLogin").permitAll()
.successHandler(loginSuccessHandler())
.failureHandler(loginFailureHandler())
.and()
.logout()
.permitAll().logoutSuccessUrl("/")
.invalidateHttpSession(true)
.and()
.exceptionHandling()
.accessDeniedPage("/403");
}
private AuthenticationFailureHandler loginFailureHandler() {
return (request, response, exception) -> {
if(exception.getMessage().contains("JDBC")) {
response.sendRedirect(request.getContextPath()+"/dbError");
} else {
response.sendRedirect(request.getContextPath()+"/loginError");
}
};
}
private AuthenticationSuccessHandler loginSuccessHandler() {
return (request, response, authentication) -> {
if(authentication.getAuthorities().size() == 0) {
log.info("User has no role.");
response.sendRedirect(request.getContextPath()+"/403");
} else if(isAdmin(authentication)) {
log.info("Admin");
response.sendRedirect(request.getContextPath()+"/admin/");
} else {
log.info("UserPage Redirecting");
response.sendRedirect(request.getContextPath()+"/user/");
}
};
}
private boolean isAdmin(Authentication auth) {
System.err.println("isadmin?? - " + auth.getAuthorities().toString());
boolean isAdmin = false;
Iterator<? extends GrantedAuthority> i = auth.getAuthorities().iterator();
while (i.hasNext()) {
if(i.next().toString().contains("ADMIN")) {
isAdmin = true;
break;
}
}
return isAdmin;
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.rainbowtape</groupId>
<artifactId>boards</artifactId>
<name>spring-mvc-hibernate-boards</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.3.4.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- url parsing :: https://mvnrepository.com/artifact/com.twitter.twittertext/twitter-text -->
<dependency>
<groupId>com.twitter.twittertext</groupId>
<artifactId>twitter-text</artifactId>
<version>3.0.1</version>
</dependency>
<!-- file upload :: https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- mail :: https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- mail :: https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- dealing with html :: https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.3</version>
</dependency>
<!-- jackson json bind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<!-- commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<!-- thymeleaf-extras-springsecurity4 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<!-- spring data jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.15.RELEASE</version>
</dependency>
<!-- thymeleap -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
<!-- spring-security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.7.Final</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- #Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>liffeyapp</finalName>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
server.contextPath=/liffeyapp
Can't fugure out, what was wrong... Would anyone help me?
Thanks in advance.
EDIT
I am adding my remote server's catalina.out - log.
23-Feb-2019 00:24:33.066 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.undeploy Undeploying context [/liffeyapp]
23-Feb-2019 00:24:43.174 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [/opt/tomcat/webapps/liffeyapp.war]
23-Feb-2019 00:24:43.194 SEVERE [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.ContextConfig.beforeStart Exception fixing docBase for context [/liffeyapp]
java.util.zip.ZipException: zip END header not found
at java.base/java.util.zip.ZipFile$Source.zerror(ZipFile.java:1527)
at java.base/java.util.zip.ZipFile$Source.findEND(ZipFile.java:1428)
at java.base/java.util.zip.ZipFile$Source.initCEN(ZipFile.java:1435)
at java.base/java.util.zip.ZipFile$Source.<init>(ZipFile.java:1266)
at java.base/java.util.zip.ZipFile$Source.get(ZipFile.java:1229)
at java.base/java.util.zip.ZipFile$CleanableResource.<init>(ZipFile.java:825)
at java.base/java.util.zip.ZipFile$CleanableResource$FinalizableResource.<init>(ZipFile.java:852)
at java.base/java.util.zip.ZipFile$CleanableResource.get(ZipFile.java:841)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:245)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:175)
at java.base/java.util.jar.JarFile.<init>(JarFile.java:341)
at java.base/sun.net.www.protocol.jar.URLJarFile.<init>(URLJarFile.java:103)
at java.base/sun.net.www.protocol.jar.URLJarFile.getJarFile(URLJarFile.java:72)
at java.base/sun.net.www.protocol.jar.JarFileFactory.get(JarFileFactory.java:99)
at java.base/sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:125)
at java.base/sun.net.www.protocol.jar.JarURLConnection.getJarFile(JarURLConnection.java:92)
at org.apache.catalina.startup.ExpandWar.expand(ExpandWar.java:130)
at org.apache.catalina.startup.ContextConfig.fixDocBase(ContextConfig.java:605)
at org.apache.catalina.startup.ContextConfig.beforeStart(ContextConfig.java:738)
at org.apache.catalina.startup.Conte
.
.
.
ContextLoader ----> ERROR: 2019-02-23 00:25:19,261 ----> Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.rainbowtape.boards.config.PersistenceConfig: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
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.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
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:4641)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5109)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:742)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:718)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:703)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:986)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1858)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:514)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
.
.
.
EDIT 2
Jave runtime verison was same.
Local
~:🛸 java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
Remote Server
root#vps*******:~# java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
I don't know what was wrong. but what I did was..
I clean the project and delete everything in .m2/.repository
and.
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
This fixed my problem.
Could it be you are compiling using Java 8 but running in Java 11?
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
jaxb was deprecated from Java 9 and then removed in Java 11 (http://openjdk.java.net/jeps/320). Maybe the Java runtime version is the difference between your local and remote server.
After springbatch integrates the mvc import interface, the transaction is abnormal, and the service layer is injected into the job to execute the transaction problem.
BatchController.class
#RestController
#RequestMapping(value = "/job")
public class BatchController {
private final JobLauncher jobLauncher;
private final Job batchGenerateJob;
#Autowired
public BatchController(JobLauncher jobLauncher, Job batchGenerateJob) {
this.jobLauncher = jobLauncher;
this.batchGenerateJob = batchGenerateJob;
}
#GetMapping(value = "/{cid}")
public AjaxObj batchgenbycid(#PathVariable String cid) {
if (StringUtils.isBlank(cid) || Integer.parseInt(cid) == 0) {
return ResultUtil.fail("请在左侧点击栏目");
}
JobParameters jobParameters = new JobParametersBuilder()
.addString("channelId", cid)
.addString("siteId", Integer.toString(1))
.addString("runtime", "最后执行时间:" + DateFormatUtils.format(new Date(), "yyyy_MM_dd_HH_mm_ss"))
.toJobParameters();
try {
jobLauncher.run(batchGenerateJob, jobParameters);
} catch (JobExecutionAlreadyRunningException e) {
e.printStackTrace();
} catch (JobRestartException e) {
e.printStackTrace();
} catch (JobInstanceAlreadyCompleteException e) {
e.printStackTrace();
} catch (JobParametersInvalidException e) {
e.printStackTrace();
}
return ResultUtil.success();
}
}
** BatchNewsConfig.class **
#Configuration
#EnableBatchProcessing
#EnableTransactionManagement
public class BatchNewsConfig implements StepExecutionListener {
public static final String SITE_ID = "siteId";
public static final String CHANNEL_ID = "channelId";
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
private final JobRepository jobRepository;
private Map<String, JobParameter> parameterMap;
#Autowired
public BatchNewsConfig(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, JobRepository jobRepository) {
this.jobBuilderFactory = jobBuilderFactory;
this.stepBuilderFactory = stepBuilderFactory;
this.jobRepository = jobRepository;
}
#Bean
public JobLauncher jobLauncher() {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
return jobLauncher;
}
#Bean
public Job batchGenerateJob() {
return jobBuilderFactory.get("batchGenerateJob")
//获取站点信息
.start(getSiteParameterStep())
.build();
}
#Bean
public Step getSiteParameterStep() {
return stepBuilderFactory.get("getChannelIdParameterStep")
.listener(this)
.tasklet(new Tasklet() {
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
String channelStr = parameterMap.get(CHANNEL_ID).toString();
Integer cid = Integer.valueOf(channelStr);
System.out.println(cid);
return RepeatStatus.FINISHED;
}
}).build();
}
#Override
public void beforeStep(StepExecution stepExecution) {
parameterMap = stepExecution.getJobParameters().getParameters();
}
#Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}
** Console output Can run**
16:37:42,840 INFO SimpleJobLauncher:133 - Job: [SimpleJob: [name=batchGenerateJob]] launched with the following parameters: [{channelId=368, siteId=1, runtime=最后执行时间:2018_12_20_16_37_42}]
16:37:42,913 INFO SimpleStepHandler:146 - Executing step: [getChannelIdParameterStep]
368
16:37:42,950 INFO SimpleJobLauncher:136 - Job: [SimpleJob: [name=batchGenerateJob]] completed with the following parameters: [{channelId=368, siteId=1, runtime:2018_12_20_16_37_42}] and the following status: [COMPLETED]
```
### When I injected the Service, I executed the error again.
** IChannelBatchService **
```java
import cn.dahe.model.Channel;
import java.util.Set;
public interface IChannelBatchService{
Channel get(int id);
Set<Integer> getAllChildrenByCid(int cid);
}
** ChannelBatchService **
import cn.dahe.dao.IChannelDao;
import cn.dahe.model.Channel;
import cn.dahe.service.IChannelBatchService;
import com.google.common.collect.Sets;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
#Service("channelBatchService")
public class ChannelBatchService implements IChannelBatchService {
#Resource
private IChannelDao channelDao;
#Override
public Channel get(int id) {
return channelDao.get(id);
}
#Override
public Set<Integer> getAllChildrenByCid(int cid) {
return getChildrenCid(cid, Sets.newHashSet());
}
/**
* #param cid
* #param cidsSet
*/
private Set<Integer> getChildrenCid(int cid, Set<Integer> cidsSet) {
cidsSet.add(cid);
List<Channel> channels = channelDao.getChannelByPid(cid);
if (channels != null && !channels.isEmpty()) {
for (Channel channel : channels) {
cidsSet.add(channel.getId());
cidsSet = getChildrenCid(channel.getId(), cidsSet);
}
}
return cidsSet;
}
}
add service
#Configuration
#EnableBatchProcessing
#EnableTransactionManagement
public class BatchNewsConfig implements StepExecutionListener {
public static final String SITE_ID = "siteId";
public static final String CHANNEL_ID = "channelId";
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
private final JobRepository jobRepository;
private final IChannelBatchService iChannelBatchService;
private Map<String, JobParameter> parameterMap;
public BatchNewsConfig(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, JobRepository jobRepository, IChannelBatchService iChannelBatchService) {
this.jobBuilderFactory = jobBuilderFactory;
this.stepBuilderFactory = stepBuilderFactory;
this.jobRepository = jobRepository;
this.iChannelBatchService = iChannelBatchService;
}
#Bean
public JobLauncher jobLauncher() {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
return jobLauncher;
}
#Bean
public Job batchGenerateJob() {
return jobBuilderFactory.get("batchGenerateJob")
.start(getSiteParameterStep())
.build();
}
#Bean
public Step getSiteParameterStep() {
return stepBuilderFactory.get("getChannelIdParameterStep")
.listener(this)
.tasklet(new Tasklet() {
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
String channelStr = parameterMap.get(CHANNEL_ID).toString();
Integer cid = Integer.valueOf(channelStr);
System.out.println(cid);
Channel channel = iChannelBatchService.get(cid);
System.out.println(channel);
return RepeatStatus.FINISHED;
}
}).build();
}
/**
* 执行前获取JobParameters
*
* #param stepExecution
*/
#Override
public void beforeStep(StepExecution stepExecution) {
parameterMap = stepExecution.getJobParameters().getParameters();
}
#Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}
** Console output **
16:48:45,539 INFO JobRepositoryFactoryBean:183 - No database type set, using meta data indicating: MYSQL
16:48:45,674 INFO SimpleJobLauncher:195 - No TaskExecutor has been set, defaulting to synchronous executor.
16:48:45,735 INFO SimpleJobLauncher:133 - Job: [SimpleJob: [name=batchGenerateJob]] launched with the following parameters: [{channelId=368, siteId=1, runtime=2018_12_20_16_48_45}]
16:48:45,792 INFO SimpleStepHandler:146 - Executing step: [getChannelIdParameterStep]
368
16:48:45,811 ERROR AbstractStep:229 - Encountered an error executing step getChannelIdParameterStep in job batchGenerateJob
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder#b675ab] for key [{
CreateTime:"2018-12-20 16:48:36",
ActiveCount:2,
PoolingCount:0,
CreateCount:2,
DestroyCount:0,
CloseCount:18,
ConnectCount:20,
Connections:[
]
}] bound to thread [SimpleAsyncTaskExecutor-1]
at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:377)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:461)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy45.get(Unknown Source)
at cn.dahe.batch.BatchNewsConfig$1.execute(BatchNewsConfig.java:88)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:272)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148)
at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392)
at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder#b675ab] for key [{
CreateTime:"2018-12-20 16:48:36",
ActiveCount:2,
PoolingCount:0,
CreateCount:2,
DestroyCount:0,
CloseCount:18,
ConnectCount:20,
Connections:[
]
}] bound to thread [SimpleAsyncTaskExecutor-1]
at org.springframework.transaction.support.TransactionSynchronizationManager.bindResource(TransactionSynchronizationManager.java:190)
at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:516)
... 26 more
16:48:45,827 INFO SimpleJobLauncher:136 - Job: [SimpleJob: [name=batchGenerateJob]] completed with the following parameters: [{channelId=368, siteId=1, runtime=2018_12_20_16_48_45}] and the following status: [FAILED]
** prom.xml **
<dependencies>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.6</version>
</dependency>
<!-- SPRING -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.16.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.16.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<!-- spring orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.1.3</version>
</dependency>
<!-- AOP begin -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
<scope>runtime</scope>
</dependency>
<!-- AOP end -->
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.1.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.1-GA</version>
</dependency>
<!-- LOGGING end -->
<!-- GENERAL UTILS begin -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
<!-- google java library -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<!-- gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<!-- TEST begin -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.2.9</version>
</dependency>
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>2.7.27</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j-light</artifactId>
<version>2.0</version>
</dependency>
Seems you have multiple transaction managers. In such a case, you can specify the transaction manager for tasklets explicitly.
<tasklet transaction-manager="transactionManager">
#EnableBatchProcessing automatically registers a transaction manager. You can change transaction manager that batch uses simply by implementing the BatchConfigurer interface.
I have built this multiple modules web application with spring 4.2.6, if I run it with tomcat7 maven plugin it will run perfectly, I can reach controllers and even read data from datasource but if I try to run it on eclipse tomcat7 server I will get this exception and the application doesn't start:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionInterceptor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'transactionManager' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
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.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:381)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d77bfca6.transactionInterceptor(<generated>)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.transactionAdvisor(ProxyTransactionManagementConfiguration.java:45)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d77bfca6.CGLIB$transactionAdvisor$0(<generated>)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d77bfca6$$FastClassBySpringCGLIB$$7634146e.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d77bfca6.transactionAdvisor(<generated>)
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.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 42 more
Caused by: java.lang.IllegalArgumentException: Property 'transactionManager' is required
at org.springframework.transaction.interceptor.TransactionAspectSupport.afterPropertiesSet(TransactionAspectSupport.java:195)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 61 more
this is my pom:
<properties>
<webapp.name>users-api</webapp.name>
<hibernate.version>4.3.6.Final</hibernate.version>
<spring.version>4.2.6.RELEASE</spring.version>
</properties>
<!-- <parent>
<groupId>com.tecnocasa</groupId>
<artifactId>users</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent> -->
<dependencies>
<!-- START SPRING DEPENDENCIES -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- END SPRING DEPENDENCIES -->
<!-- START OTHER DEPENDENCIES -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.196</version>
</dependency>
<dependency>
<groupId>com.myproject</groupId>
<artifactId>myproject-serviceimpl</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.myproject</groupId>
<artifactId>utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts-core</artifactId>
<version>1.14.0</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.1</version>
<scope>provided</scope>
</dependency>
<!-- END OTHER DEPENDENCIES -->
<dependency>
<groupId>com.myproject</groupId>
<artifactId>myproject-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
this is my WebApplication class:
public class WebApplication implements WebApplicationInitializer{
#Override
public void onStartup( ServletContext servletContext ) throws
ServletException
{
AnnotationConfigWebApplicationContext applicationContext = new
AnnotationConfigWebApplicationContext();
AnnotationConfigWebApplicationContext rootContext = new
AnnotationConfigWebApplicationContext();
servletContext.addListener( new ContextLoaderListener( rootContext ) );
applicationContext.register( ControllerApiConfig.class );
DispatcherServlet dispatcherServlet = new DispatcherServlet( applicationContext );
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet );
dispatcher.setLoadOnStartup( 1 );
dispatcher.addMapping( "/" );
}
}
and this my CoreConfig class
#EnableTransactionManagement
#EnableJpaRepositories
#Configuration
#Import( value = { ServiceConfig.class, RepositoryConfig.class } )
public class CoreConfig
{
#Bean
public DataSource dataSource( )
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName( "oracle.jdbc.driver.OracleDriver" );
dataSource.setUrl( "jdbc:oracle:thin:#testdb:1522/myproject" );
dataSource.setUsername( "user" );
dataSource.setPassword( "psw" );
return dataSource;
}
Properties additionalProperties( )
{
Properties properties = new Properties();
properties.setProperty( "hibernate.dialect","org.hibernate.dialect.Oracle10gDialect" );
return properties;
}
#Bean
public EntityManagerFactory entityManagerFactory( )
{
HibernateJpaVendorAdapter vendorAdapter = newHibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl( false );
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect" );
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter( vendorAdapter );
factory.setPackagesToScan( "com.myproject.dto" );
factory.setDataSource( dataSource() );
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public PlatformTransactionManager transactionManager( )
{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory( entityManagerFactory() );
return transactionManager;
}
#Bean
public TransactionTemplate transactionTemplate( PlatformTransactionManager transactionManager )
{
return new TransactionTemplate( transactionManager );
}
}
LocalContainerEntityManagerFactoryBean not created context faild
Below is the error:
java.lang.IllegalStateException: Failed to load ApplicationContext at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'entityManagerFactory' defined in
com.test.spring.AppConfig: Invocation of init method failed; nested
exception is java.lang.NoSuchMethodError:
javax.persistence.spi.PersistenceUnitInfo.getSharedCacheMode()Ljavax/persistence/SharedCacheMode;
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
and code:
#ComponentScan
#Configuration
#EnableJpaRepositories("com.test.spring.repository")
public class AppConfig {
#Value("${jdbc.driverClassName}")
private String jdbcDriverClassName;
#Value("${jdbc.url}")
private String jdbcURL;
#Value("${jdbc.username}")
private String jdbcUserName;
#Value("${jdbc.password}")
private String jdbcPassword;
public static PropertySourcesPlaceholderConfigurer getPropertiesFile(String profileName) {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
String path = new StringJoiner("").add("application_dev")/*.add(profileName)*/.add(".properties").toString();
Resource location = new ClassPathResource(path);
pspc.setLocations(location);
return pspc;
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(jdbcDriverClassName);
dataSource.setUrl(jdbcURL);
dataSource.setUsername(jdbcUserName);
dataSource.setPassword(jdbcPassword);
return dataSource;
}
#Bean(name="entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("com.test.spring.domain");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
factoryBean.setJpaVendorAdapter(vendorAdapter);
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
props.put("hibernate.hbm2ddl.auto", "create");
factoryBean.setJpaProperties(props);
return factoryBean;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
//Here is the pom file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test.spring</groupId>
<artifactId>EntityExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
Since you are missing hibernate classes and libraries, try to extend your pom dependency with something like this:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.5.0</version>
</dependency>