This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I started spring mvc project and tried to use JPA there. I have class User and BasePersistable with accessors generated by #RooJavaBean.
import javax.persistence.GeneratedValue;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Persistable;
import org.springframework.roo.addon.javabean.RooJavaBean;
#RooJavaBean
#MappedSuperclass
public abstract class BasePersistable implements Persistable<Long> {
private static final long serialVersionUID = -3281161320810540373L;
#Id
#GeneratedValue
private Long id;
#Version
private Integer version;
#Override
public boolean isNew() {
return getId() == null;
}
}
and
#Entity
#RooJavaBean
public class User extends BasePersistable {
private static final long serialVersionUID = -1999311284585286126L;
private String username;
private String passwrd;
private String firstname;
private String lastname;
private String email;
#Temporal(TemporalType.TIMESTAMP)
private Calendar signupDate;
private Sex sex;
private String comment;
}
Roo definitely generate getters and setters.
I can access getId() method in code:
User user = new User();
user.getId();
But I got this error:
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.test:mvc1:war:1.0.0-BUILD-SNAPSHOT
[WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.codehaus.mojo:aspectj-maven-plugin # line 284, column 21
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building mvc1 1.0.0-BUILD-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) # mvc1 ---
[INFO] Deleting /home/zzz/ws_java/mvc1/target
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) # mvc1 ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) # mvc1 ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 6 source files to /home/zzz/ws_java/mvc1/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/zzz/ws_java/mvc1/src/main/java/com/test/mvc1/domain/User.java:[13,7] error: User is not abstract and does not override abstract method getId() in Persistable
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.831s
[INFO] Finished at: Sat Aug 11 09:56:58 NOVT 2012
[INFO] Final Memory: 16M/86M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project mvc1: Compilation failure
[ERROR] /home/zzz/ws_java/mvc1/src/main/java/com/test/mvc1/domain/User.java:[13,7] error: User is not abstract and does not override abstract method getId() in Persistable
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
It seems that there are some problems with AspectJ I think. Can anyone help?
UPD
Here is BasePersistable_Roo_JavaBean.aj
// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).
package com.test.mvc1.domain;
import com.test.mvc1.domain.BasePersistable;
privileged aspect BasePersistable_Roo_JavaBean {
public Long BasePersistable.getId() {
return this.id;
}
public void BasePersistable.setId(Long id) {
this.id = id;
}
public Integer BasePersistable.getVersion() {
return this.version;
}
public void BasePersistable.setVersion(Integer version) {
this.version = version;
}
}
By the way if to add stub method getId() to User class:
public Long getId() {
return 1L;
}
UPD 2
I cant even imagine what is wrong with the project. I add new dependency in pom file and maven does not download it. Here is my pom:
<?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.test</groupId>
<artifactId>mvc1</artifactId>
<name>mvc1</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.7</java-version>
<spring.version>3.1.0.RELEASE</spring.version>
<aspectj.version>1.6.12</aspectj.version>
<org.slf4j-version>1.5.10</org.slf4j-version>
<roo.version>1.2.1.RELEASE</roo.version>
<data-jpa.version>1.1.0.M1</data-jpa.version>
<tiles.version>2.2.2</tiles.version>
<hibernate-jpa-api.version>1.0.1.Final</hibernate-jpa-api.version>
<hibernate-entity-manager.version>4.1.0.Final</hibernate-entity-manager.version>
<aspectj-plugin.version>1.2</aspectj-plugin.version>
<eclipse-plugin.version>2.7</eclipse-plugin.version>
<compiler-plugin.version>2.3.2</compiler-plugin.version>
<!-- database properties start -->
<database.url>jdbc:mysql://localhost:3306/mvctest</database.url>
<database.username>root</database.username>
<database.password />
<database.driverClassName>com.mysql.jdbc.Driver</database.driverClassName>
<database.type>MYSQL</database.type>
<!-- database properties end -->
</properties>
<repositories>
<repository>
<id>spring-maven-release</id>
<name>Spring Maven Release Repository</name>
<url>http://maven.springframework.org/release</url>
</repository>
<repository>
<id>spring-maven-milestone</id>
<name>Spring Maven Milestone Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
<repository>
<id>spring-roo-repository</id>
<name>Spring Roo Repository</name>
<url>http://spring-roo-repository.springsource.org/release</url>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.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>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${data-jpa.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<!-- Hibernate/Jpa -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entity-manager.version}</version>
</dependency>
<!-- Database -->
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<!-- Roo -->
<dependency>
<groupId>org.springframework.roo</groupId>
<artifactId>org.springframework.roo.annotations</artifactId>
<version>${roo.version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.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>servlet-api</artifactId>
<version>2.5</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>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>${tiles.version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<!-- version is used because of Roo 1.2.1.RELEASE requirement -->
<!-- remove it when fixed -->
<version>${eclipse-plugin.version}</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<wtpversion>2.0</wtpversion>
<additionalBuildcommands>
<buildCommand>
<name>org.eclipse.ajdt.core.ajbuilder</name>
<arguments>
<aspectPath>org.springframework.aspects</aspectPath>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
</buildCommand>
</additionalBuildcommands>
<additionalProjectnatures>
<projectnature>org.eclipse.ajdt.ui.ajnature</projectnature>
<projectnature>com.springsource.sts.roo.core.nature</projectnature>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>${aspectj-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
<source>1.6</source>
<target>1.6</target>
</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>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.4.v20120524</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<junitArtifactName>org.junit:com.springsource.org.junit</junitArtifactName>
<excludes>
<exclude>**/*_Roo_*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Here is my servlet-context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- ========================= GENERAL DEFINITIONS ========================= -->
<mvc:annotation-driven />
<mvc:resources location="/resources/" mapping="/resources/**"/>
<context:property-placeholder location="classpath*:META-INF/spring/*.properties" />
<context:component-scan base-package="com.test.mvc1.web">
<context:exclude-filter expression=".*_Roo_.*" type="regex"/>
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<jpa:repositories base-package="com.test.mvc1.repository" />
<!-- ========================= VIEW DEFINITIONS ========================= -->
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
<!-- ========================= TILES DEFINITIONS ========================= -->
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/defs/tiles.xml</value>
</list>
</property>
</bean>
<!-- ========================= Persistence configuration ========================= -->
<jpa:repositories base-package="com.test.mvc1.repository" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driverClassName}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="validationQuery" value="SELECT NOW()" />
</bean>
<bean id="entityManagerFactory" depends-on="liquibase" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.test.mvc1.domain, ${database.packagesToScan}" />
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">${database.namingStrategy}</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">${database.showsql}</prop>
<prop key="hibernate.hbm2ddl.auto">${database.hbm2ddl}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
</props>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${database.type}" />
<property name="showSql" value="${database.showsql}" />
<property name="generateDdl" value="false" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />
<bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase">
<property name="changeLog" value="classpath:META-INF/db/changelog.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Here is errors:
2012-08-12 10:42:24.250:WARN:/:unavailable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
Caused by:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
Caused by:
javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
Caused by:
org.hibernate.AnnotationException: No identifier specified for entity: com.test.mvc1.domain.User
at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:276)
2012-08-12 10:42:24.525:INFO:oejs.AbstractConnector:Started SelectChannelConnector#0.0.0.0:8080
[INFO] Started Jetty Server
I need help!
I suppose that the matter is versions conflicts in some dependencies or plugins.
EDIT: Updating the answer as pre modified question...
org.hibernate.AnnotationException: No identifier specified for entity: com.malykhinvi.mvc1.domain.User
So here the error says that your entity com.malykhinvi.mvc1.domain.User doesn't have an #Id annotation to depict the primary key.
Can you try placing for BasePersistable
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
Related
We have file payment.jar that developed with Spring Framework 3.1.2 . We need to use it as a dependency on a new project that its version is Spring Framework 5.x .
Problem: When payment.jar used as a dependency, the payment.jar transitive dependencies add to project class-path so in cause conflicting Spring Framework 3 and Spring Framework 5.
I tried solutions:
big fat jar:
create-an-executable-jar-with-dependencies-using-maven
there is no success, the fat JAR, adds Spring Framework 3 to project. (what I am doing wrong!)
excluding payment Spring Framework 3.1.2 dependency in new project:
because of using spring-ibatis implementation in payment.jar it is not worked. Spring Framework new versions do not support ibatis.
Error:
Caused by: java.lang.ClassNotFoundException:
org.springframework.orm.ibatis.support.SqlMapClientDaoSupport
my requirement:
I need to use payment.jar (with Spring Framework 3.1.2) as a dependency on new project with Spring Framework 5.x without problem mentioned above.
If the Spring versions are as incompatible as it sounds as though they are, you're probably going to have to recompile either the jar or the project so that they're using the same version of Spring.
If that's impossible (e.g. if you don't have source for the jar), you might be able to wrap the payment jar up in a microservice so that it's running in a different process, and talk to it via XML-RPC or SOAP.
Your wish
I need to use payment.jar (with Spring Framework 3.1.2) as a
dependency on new project with Spring Framework 5.x without problem
mentioned above.
You cannot do it. Because the mismatching of version of dependencies. It is not backward compatible between many things, many version of iBatis, Spring Framework, payment.jar and other dependencies.
You must upgrade it manually.
The best option for this is to upgrade this manually.
Even if you will do this with Spring 3 jar, you will land with a lot of issues while compiling and running.
The ideal solution would be to update everything to Spring 5 or deploy payment.jar separately as a microservice as others mentioned. But this is not the core part of your question, maybe you have some unavoidable requirements. So as #tomer-shahar said the solution is to use maven shade plugin.
This kind of conflicts happen a lot when you use open source libraries sharing the same libraries but with different versions.
The maven shade plugin allows renaming/recolocating the packages selected avoiding conflicts within versions. The drawback is that some classes will be duplicated (so it is far from ideal). See the example below:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>spring321-payment-shaded</finalName>
<relocations>
<relocation>
<pattern>spring.package</pattern>
<shadedPattern>shaded.spring.package</shadedPattern>
</relocation>
</relocations>
<artifactSet>
<includes>
<include>*:*</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
And then add as dependency to the Spring 5 project this shaded library with all the renaming/rellocation done. I used this interesting article where all the details are fully described.
I suggest you to convert your jar in Spring 5 and MyBatis. I think it's the better solution in terms of mantenibility and compatibility. Migrate to iBatis to MyBatis does not a big problem, I think.
I had a working project that uses Spring 5 and My-Batis 3. I encountered some problem to configure it, but in the end, I solved everything. Just check the POM configuration and the Spring configuration.
POM configuration
In the following lines of code, you can read the project pom (I removed useless part of the file for your problem).
<?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>it.dummy</groupId>
<artifactId>dummy</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Dummy App</name>
<url>http://maven.apache.org</url>
<properties>
<java-source.version>1.8</java-source.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.skip.tests>true</maven.skip.tests>
<servlet-api.version>3.1.0</servlet-api.version>
<spring.version>5.0.7.RELEASE</spring.version>
<swagger.version>2.9.2</swagger.version>
<jackson.version>2.9.6</jackson.version>
<mybatis-spring>1.3.2</mybatis-spring>
<junit.version>4.12</junit.version>
<frontend-maven-plugin.version>1.4</frontend-maven-plugin.version>
<mapstruct.version>1.2.0.Final</mapstruct.version>
</properties>
<dependencies>
<!-- -->
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
<!-- https://github.com/mapstruct/mapstruct -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<!-- cucumber -->
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.14.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<!-- test -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-rest-core -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-core</artifactId>
<version>3.0.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security Artifacts - START -->
<!-- http://mvnrepository.com/artifact/org.springframework.security/spring-security-web%20 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework.security/spring-security-config%20 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security Artifacts - END -->
<!-- Swagger - BEGIN -->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- Swagger - END -->
<!-- json -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9</version>
</dependency>
</dependencies>
</project>
Just remember to check always the dependencies tree to avoid to have indesiderate Spring jars.
Spring configuration
I have different file for Spring configuration. I attach only the interesting one.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="URL" value="jdbc:oracle:thin:#xxx:yyy:zzz" />
<property name="user" value="aaa"/>
<property name="password" value="bbb"/>
<property name="connectionCachingEnabled" value="true" />
</bean>
<bean id="transactionManagerNG" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactoryNG" class="org.mybatis.spring.SqlSessionFactoryBean" name="SqlSessionFactoryOrarioStandardDao">
<property name="dataSource" ref="dataSource" />
<!-- 1. Where is the xml for query's definitions -->
<property name="mapperLocations" value="classpath:com/dummy/persistence/dao/*.xml" />
<!-- 2. My-batis configuration -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 3. My-batis type alias package -->
<property name="typeAliasesPackage" value="com.dummy.persistence.model" />
</bean>
<!-- 4. needed to parse Java DAO interfaces -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="it.insiel.sanita.farmacieng.persistence.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryNG"/>
</bean>
<tx:annotation-driven/>
</beans>
In the above Spring file you will find:
How I defined the location where put XML for SQL queries (comment 1)
How I use My-batis configuration (comment 2)
How I defined the type alias package (comment 3)
How I defined the DAO interfaces
Last but not least the My-batis configuration file mybatis-config.xml, that I put in the same folder of Spring configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- http://mybatis.org/dtd/ -->
<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="cacheEnabled" value="true"/>
<setting name="defaultStatementTimeout" value="3000"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="jdbcTypeForNull" value="NULL" />
</settings>
</configuration>
Though I have not done this with spring specifically, the general concept of what you are trying to accomplish is called shading.
https://softwareengineering.stackexchange.com/questions/297276/what-is-a-shaded-java-dependency
The reason the fat jar didn't work is because all jars were loaded to the classpath, and the wrong one will be chosen for at least on of the dependencies.
What you need to do is change the package name in both a dependency and the depending jar (in your case spring 3 and payment jar), so you basically end up with two pairs of dependencies that don't overlap.
This is relatively simple to do in maven and similar tools. See the link for more details.
I have a jar which reads a excel template. If I use Maven shade to package without using resources filter and execute my jar, it is ok; However, I got some exception after I use Maven resources filter! The exception which occurs when I execute jar is as follows:
2018-01-05 11:20:45,631 [main] INFO tw.com.test.aop.SystemPointcuts- AOP Aro
und start : ServiceImpl.ServiceImpl.genExcel(..)(). param : 20171106,20171112
Exception in thread "main" org.apache.poi.openxml4j.exceptions.InvalidOperationE
xception: Can't open the specified file: 'C:\Users\seesaw\AppData\Local\Temp\Wee
klyTelecomAnalysis2553686971923113156.xlsx'
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:131)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:246)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:200)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.ja
va:90)
at tw.com.test.weeklyTelecomAnalysis.service.ServiceImpl.genExcel(Ser
viceImpl.java:73)
at tw.com.test.weeklyTelecomAnalysis.service.ServiceImpl$$FastClassBy
SpringCGLIB$$9d7f5cb8.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:2
04)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation
.invokeJoinpoint(CglibAopProxy.java:738)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:157)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.p
roceed(MethodInvocationProceedingJoinPoint.java:85)
at tw.com.test.aop.SystemPointcuts.execAround(SystemPointcuts.java:59
)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMet
hodWithGivenArgs(AbstractAspectJAdvice.java:629)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMet
hod(AbstractAspectJAdvice.java:618)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAro
undAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invok
e(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterce
ptor.intercept(CglibAopProxy.java:673)
at tw.com.test.weeklyTelecomAnalysis.service.ServiceImpl$$EnhancerByS
pringCGLIB$$1731d8a8.genExcel(<generated>)
at tw.com.test.weeklyTelecomAnalysis.main.Entry.main(Entry.java:45)
Caused by: java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:219)
at java.util.zip.ZipFile.<init>(ZipFile.java:149)
at java.util.zip.ZipFile.<init>(ZipFile.java:163)
at org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipFile(ZipHelper
.java:157)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:129)
... 23 more
here's my pom.xml
<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>tw.com.test</groupId>
<artifactId>WeeklyTelecomAnalysis</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>WeeklyTelecomAnalysis</name>
<profiles>
<profile>
<id>prod</id>
<properties>
<pps.datasource>jdbc:oracle:thin:#11.111.11.111:1111:MYPROD</pps.datasource>
<pps.username>xxxxxx</pps.username>
<pps.password>xxxxxx</pps.password>
</properties>
</profile>
</profiles>
<properties>
<!-- 執行類別 -->
<mainClass>tw.com.test.weeklyTelecomAnalysis.main.Entry</mainClass>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jdk.target.version>1.7</jdk.target.version>
<maven.compiler.source>${jdk.target.version}</maven.compiler.source>
<maven.compiler.target>${jdk.target.version}</maven.compiler.target>
<org.springframework.version>4.3.8.RELEASE</org.springframework.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- commons -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>com.springsource.org.apache.commons.dbcp</artifactId>
<version>1.2.2.osgi</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>com.springsource.org.apache.commons.lang</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>com.springsource.org.apache.commons.pool</artifactId>
<version>1.5.3</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- others -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.apache.poi</groupId> -->
<!-- <artifactId>poi</artifactId> -->
<!-- <version>3.16</version> -->
<!-- </dependency> -->
<!-- <dependency> -->
<!-- <groupId>org.apache.poi</groupId> -->
<!-- <artifactId>poi-ooxml</artifactId> -->
<!-- <version>3.16</version> -->
<!-- </dependency> -->
<!-- 安裝ojdbc6.jar至本地maven : mvn install:install-file -Dfile=ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>com.springsource.org.junit</artifactId>
<version>4.9.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>com.springsource.repository.bundles.external</id>
<name>EBR External Release Repository</name>
<url>http://repository.springsource.com/maven/bundles/external</url>
</repository>
<repository>
<id>com.springsource.repository.libraries.external</id>
<name>EBR Libraries Release Repository</name>
<url>http://repository.springsource.com/maven/libraries/external</url>
</repository>
</repositories>
<build>
<finalName>WeeklyTelecomAnalysis</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.7.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>${mainClass}</mainClass>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.schemas</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
here's my application-context.xml which is for spring framework and jdbc config, I use Maven resource filter to replace some parameter, but after I do it, I got some error which is as mentioned above.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:aop="http://www.springframework.org/schema/aop"
xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- enable autowiring of components -->
<context:component-scan base-package="tw.com.test" />
<context:annotation-config />
<aop:aspectj-autoproxy />
<!-- MYPROD -->
<bean id="pps_dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" lazy-init="false">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="${pps.datasource}" />
<property name="username" value="${pps.username}" />
<property name="password" value="${pps.password}" />
<property name="maxActive" value="20" />
<property name="maxIdle" value="0" />
<property name="maxWait" value="180000" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="300" />
<property name="logAbandoned" value="true" />
<property name="testOnBorrow" value="true" />
<property name="testWhileIdle" value="true" />
<property name="validationQuery" value="select 1 from dual" />
</bean>
<bean id="pps_sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="pps_dataSource" />
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
</bean>
<bean id="pps_sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="pps_sqlSessionFactory" />
</bean>
<bean id="pps_stsMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionTemplateBeanName" value="pps_sqlSessionTemplate" />
<property name="basePackage" value="tw.com.test.weeklyTelecomAnalysis.manual.pps" />
</bean>
</beans>
here's the program which read the excel template
public XSSFWorkbook genExcel(String fromDate, String toDate) throws Exception {
// get Excel template
Resource resource = new ClassPathResource("excel/WeeklyTelecomAnalysis.xlsx");
File excel = stream2file(resource.getInputStream(), "WeeklyTelecomAnalysis", ".xlsx");
XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(excel);
// style
this.setStyle(workbook);
XSSFSheet sheet1 = workbook.getSheet("WeeklyTelecomAnalysis"); // template
XSSFSheet sheet2 = workbook.createSheet("detail");
// start
createSheet1(sheet1, fromDate, toDate);
createSheet2(sheet2, fromDate, toDate);
return workbook;
}
public static File stream2file (InputStream in, String prefix, String suffix) throws IOException {
final File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
}
return tempFile;
}
could anyone help me?
It would seem like your .xlsx contains some values that shouldn't be replaced but are replaced by filtering, breaking the file.
I just want to use "mvn clean package -Pprod"to filter the parameters that are url,username and password in the application-context.xml rather than the excel template.
Given that, just do
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.xlsx</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
to only filter your xml configs, leaving your excel template out.
I am not able to resolve the issue am getting.
Full stacktrace:
12:14:08.172 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
12:14:08.178 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
12:14:08.178 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
12:14:08.183 [main] INFO o.s.c.s.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#24273305: startup date [Thu Mar 16 12:14:08 GMT 2017]; root of context hierarchy
12:14:08.222 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
12:14:08.223 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
12:14:08.223 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
12:14:08.233 [main] INFO o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [org/postprocessor/config/dataSupport.xml]
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [org/postprocessor/config/dataSupport.xml]; nested exception is java.io.FileNotFoundException: class path resource [org/postprocessor/config/dataSupport.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:252)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:612)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:513)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.postprocessor.dao.DaoMain.main(DaoMain.java:12)
Caused by: java.io.FileNotFoundException: class path resource [org/postprocessor/config/dataSupport.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 13 more
Bean config file dataSupport.xml is here:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- <bean/> definitions here -->
<context:annotation-config />
<context:component-scan base-package="org.postprocessor.dao" />
<context:component-scan base-package="org.postprocessor.model" />
<context:component-scan base-package="org.postprocessor.util" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver"
/> <property name="url" value="jdbc:derby:postprocessor;create=true;" />
<!-- <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" />
<property name="url" value="jdbc:derby://localhost:1527/db;create=true;" /> -->
<property name="initialSize" value="1" />
<property name="maxActive" value="1" />
</bean>
<bean id="daoImpl" class="org.postprocessor.dao.DaoImpl" scope="prototype">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>resourceBundles/general</value>
<value>resourceBundles/codeLists/codelist_eortcqlqc30</value>
<value>resourceBundles/codeLists/codelist_eortcqlqlc13</value>
<value>resourceBundles/codeLists/codelist_eq5d3l</value>
<value>resourceBundles/codeLists/codelist_eq5d5l</value>
<value>resourceBundles/codeLists/codelist_noncompletedquestionnaires</value>
<value>resourceBundles/codeLists/codelist_pgis</value>
<value>resourceBundles/codeLists/codelist_silc</value>
</list>
</property>
</bean>
snipped from pom.xml:
<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>SBP</groupId>
<artifactId>SBP</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gt20047</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-asm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/asm/asm-all -->
<dependency>
<groupId>asm</groupId>
<artifactId>asm-all</artifactId>
<version>3.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.derby/derbynet -->
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbynet</artifactId>
<version>10.12.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.derby/derbyclient -->
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.12.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<finalName>gt20047</finalName>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3</version>
<configuration>
<archive>
<manifest>
<!-- Jar file entry point -->
<mainClass>org.postprocessor.dao.DaoMain</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
am not able to figure out where is the issue, my jar file doesn't have this config folder
DaoMain.java
package org.postprocessor.dao;
import java.io.File;
import org.postprocessor.util.FileZipper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DaoMain {
public static void main(String[] args) {
ApplicationContext ctx= new ClassPathXmlApplicationContext("classpath:/org/postprocessor/config/dataSupport.xml");
DaoImpl daoImpl=null;
FileZipper fileZipper=null;
try{
daoImpl= ctx.getBean("daoImpl",DaoImpl.class);
fileZipper= ctx.getBean("fileZipper",FileZipper.class);
daoImpl.startProcess();
fileZipper.zipFile(new File("").getAbsolutePath()+"/output");
}
catch(Exception e){
e.printStackTrace();
}
finally{
((ClassPathXmlApplicationContext) ctx).close();
}
}
}
How to solve this issue?
Looks like the main problem is at this line:
new ClassPathXmlApplicationContext("classpath:/org/postprocessor/config/dataSupport.xml");
You are trying to build context from classpath. Thus you have to locate your config file accessible from a classpath of your project.
You using Maven for building your project. Maven has defined project structure for code sources:
/src/main/java
and for resources:
/src/main/resorces
You can find more here: Introduction to the Standard Directory Layout
If you want to make your file accessible from classpath you have to put it exactly under - resources/ folder:
Now you main() will be, something like:
public static void main(String[] args) {
ApplicationContext ctx= new ClassPathXmlApplicationContext("classpath:config/dataSupport.xml");
Object dataSource = ctx.getBean("userRepo");
System.out.println(dataSource.getClass().getName());
// use your beans here
I created just demo bean. And here is output:
2017-03-20 15:22:40 INFO ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#16f65612: startup date [Mon Mar 20 15:22:40 EET 2017]; root of context hierarchy
2017-03-20 15:22:40 INFO XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [config/dataSupport.xml]
demo.repository.UserRepository
BTW you can use try with resources for application context:
try(ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("classpath:config/dataSupport.xml")) {
// use your beans here
}
Additional resources:
using classpath: in spring
Java Spring - How to use classpath to specify a file location?
Your XML files are not well formed.
While I do not know if this is the issue, it may be the root cause of why your project is not taking the files correctly in the first place.
Your <beans> tag does not have a closing tag. Try putting </beans> at the end of the file.
Also, your pom.xml file has the same issue. The <project> is not closed. Try putting </project> at the end of the file.
I think the following should work:
ApplicationContext ctx= new ClassPathXmlApplicationContext("org/postprocessor/config/dataSupport.xml");
You don't need to specify "classpath" since you already use ClassPathXmlApplicationContext, and you have extra slash in the beginning.
move:
src/org/postprocessor/config/dataSupport.xml
to:
src/main/resources/org/postprocessor/config/dataSupport.xml
By default maven-compiler-plugin not includes non-java files. which left you with two options.
1. move your resource files (.properties, .xml etc) to "src/main/resources" (recomended.)
2. use maven resource plugin
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/path/where/you/want</outputDirectory>
<resources>
<resource>
<directory>${basedir}</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
I did simple application on Spring MVC and Tomcat. It also have connection to DB. Code of my app in bottom. When I run it on PC it work perfect but when I deploy it on heroku I get an
Application Error:
An error occurred in the application and your page could not be
served. Please try again in a few moments. If you are the application
owner, check your logs for details.
I have errors when it pushing and below is my heroku log:
2016-11-02T18:12:07.193103+00:00 heroku[web.1]: Starting process with command `java -cp target/classes/:target/dependency/* com.shop.cond.MainController`
2016-11-02T18:12:09.518875+00:00 app[web.1]: Setting JAVA_TOOL_OPTIONS defaults based on dyno size. Custom settings will override them.
2016-11-02T18:12:09.522830+00:00 app[web.1]: Picked up JAVA_TOOL_OPTIONS: -Xmx350m -Xss512k -Dfile.encoding=UTF-8
2016-11-02T18:12:09.720990+00:00 app[web.1]: Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/ui/Model
2016-11-02T18:12:09.715926+00:00 app[web.1]: Error: A JNI error has occurred, please check your installation and try again
2016-11-02T18:12:09.721171+00:00 app[web.1]: at java.lang.Class.getDeclaredMethods0(Native Method)
2016-11-02T18:12:09.721268+00:00 app[web.1]: at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
2016-11-02T18:12:09.721330+00:00 app[web.1]: at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
2016-11-02T18:12:09.721391+00:00 app[web.1]: at java.lang.Class.getMethod0(Class.java:3018)
2016-11-02T18:12:09.721513+00:00 app[web.1]: at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
2016-11-02T18:12:09.721451+00:00 app[web.1]: at java.lang.Class.getMethod(Class.java:1784)
2016-11-02T18:12:09.721715+00:00 app[web.1]: Caused by: java.lang.ClassNotFoundException: org.springframework.ui.Model
2016-11-02T18:12:09.721576+00:00 app[web.1]: at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
2016-11-02T18:12:09.721778+00:00 app[web.1]: at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
2016-11-02T18:12:09.721838+00:00 app[web.1]: at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
2016-11-02T18:12:09.721902+00:00 app[web.1]: at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
2016-11-02T18:12:09.721988+00:00 app[web.1]: at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
2016-11-02T18:12:09.722057+00:00 app[web.1]: ... 7 more
2016-11-02T18:12:09.843097+00:00 heroku[web.1]: State changed from starting to crashed
2016-11-02T18:12:09.847741+00:00 heroku[web.1]: Process exited with status 1
2016-11-02T18:12:11.191694+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=bestmuzonproject.herokuapp.com request_id=0c01c995-e9b1-4c86-84bb-9b4abbdcabd4 fwd="178.94.207.167" dyno= connect= service= status=503 bytes=
2016-11-02T18:12:11.429322+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=bestmuzonproject.herokuapp.com request_id=cf7c5536-8106-46e5-9e4c-db48d17242cf fwd="178.94.207.167" dyno= connect= service= status=503 bytes=
What it can be? Why I can get this errors?
My code. Main Controller:
package com.shop.cond;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.shop.cond.model.Product;
import com.shop.cond.service.ProductService;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
#Controller
#RequestMapping("/")
public class MainController {
private ProductService productService;
#Autowired(required=true)
#Qualifier(value="productService")
public void setPersonService(ProductService ps){
this.productService = ps;
}
#RequestMapping(method = RequestMethod.GET)
public String index(Model model) {
return "index";
}
#RequestMapping(value = {"/home"}, method = RequestMethod.GET)
public String homePage() {
System.out.println("home");
return "forward:/";
}
#RequestMapping(value = "/about", method = RequestMethod.GET)
public String aboutPage(Model model) {
System.out.println("about");
return "forward:/";
}
#ResponseBody
#RequestMapping(value = "/products/listProducts", method = RequestMethod.GET)
public List<Product> getProducts() {
List<Product> products = this.productService.listProducts();
return products;
}
#RequestMapping(value = {"/products"}, method = RequestMethod.GET)
public String productsPage() {
System.out.println("products");
return "forward:/";
}
#RequestMapping(value = {"/contacts"}, method = RequestMethod.GET)
public String contactsPage() {
System.out.println("contacts");
return "forward:/";
}
}
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.shop.cond</groupId>
<artifactId>OnlineShop</artifactId>
<name>OnlineShop</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>4.0.3.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
<hibernate.version>4.3.5.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- #Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</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>
<!--JSON Response-->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
<!--PostgreeSQL-->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>copy</goal></goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>com.github.jsimone</groupId>
<artifactId>webapp-runner</artifactId>
<version>8.0.30.2</version>
<destFileName>webapp-runner.jar</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</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>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>OnlineShop</server>
<path>/</path>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>1.1.1</version>
<configuration>
<assembleDirectory>target</assembleDirectory>
<programs>
<program>
<mainClass>com.shop.cond.MainController</mainClass>
<name>webapp</name>
</program>
</programs>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>assemble</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>
servlet-context:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.shop.cond" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<!--<beans:property name="url" value="jdbc:postgresql://ec2-54-235-177-62.compute-1.amazonaws.com:5432/d7pgi7nq0ue78j" />-->
<!--<beans:property name="username" value="htcxkqyeyymcxz" />-->
<!--<beans:property name="password" value="rs7Z8b4ULNa5zol8fSzJd_BNNR" />–>
-->
<beans:property name="url" value="jdbc:mysql://localhost:3306/shopDB" />
<beans:property name="username" value="arxangel192" />
<beans:property name="password" value="qwe321zxc321" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.shop.cond.model.Product</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="productDAO" class="com.shop.cond.dao.ProductDAOImpl">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="productService" class="com.shop.cond.service.ProductServiceImpl">
<beans:property name="productDAO" ref="productDAO"/>
</beans:bean>
<context:component-scan base-package="com.shop.cond" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
</beans:beans>
Procfile:
web: sh target/bin/webapp
web: java -cp target/classes/:target/dependency/* com.shop.cond.MainController
The structure of catalogs:
STRUCTURE
First, you have two web: entries in your Procfile. Use only the java -cp one if that's what you need.
The main error is java.lang.NoClassDefFoundError: org/springframework/ui/Model, which usually means you are missing a JAR file on your classpath.
Have you copied all of your dependencies into target/dependency?
Typically this is done with the following in your pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals><goal>copy-dependencies</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
If you have that config, check that your Spring dependencies are not set as provided.
I've been trying to get a simple skeleton app to run (and commit to the DB) using JPA, MySQL, Hibernate & Maven, however I'm having problems.
Listed below are my 2 trivial classes, my pom.xml, and my META-INF/persistence.xml
I can build the project without any problem (mvn clean install), however running it (mvn exec:java -Dexec.mainClass=com.foo.HelloWorld -X) causes an exception, with the following StackTrace.
Any help would be greatly appreciated!
Stacktrace:
org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. null
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:719)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:569)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:539)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. null
at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694)
... 17 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:291)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/engine/SessionImplementor;
at org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:167)
at org.hibernate.action.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:142)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:65)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:154)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:110)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:646)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:620)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:624)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:212)
at com.foo.HelloWorld.create(HelloWorld.java:32)
at com.foo.HelloWorld.main(HelloWorld.java:11)
... 6 more
I have the following two classes:
The Entity to store.
package com.foo;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Message {
#Id
#GeneratedValue
private int id;
#Basic
private String message;
public Message() {}
public Message(String message) {
this.message = message;
}
public String toString() {
return "Greeting id=" + id + ", message=" + message;
}
}
The Application:
package com.foo;
public class HelloWorld {
private javax.persistence.EntityManagerFactory emf;
private javax.persistence.EntityManager em;
private String PERSISTENCE_UNIT_NAME = "hello-world";
public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
hello.initEntityManager();
hello.create();
// hello.read();
hello.closeEntityManager();
}
private void initEntityManager() {
emf = javax.persistence.Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
}
private void closeEntityManager() {
em.close();
emf.close();
}
private void create() {
em.getTransaction().begin();
Message hello = new Message("hello world");
Message bye = new Message("goodbye, world");
Message[] messages = new Message[] {hello, bye};
for (Message m : messages) {
em.persist(m);
}
em.getTransaction().commit();
}
// private void read() {
// Message m = (Message)em.createQuery("select m from Message m").getSingleResult();
// System.out.println("Query returned: " + m);
// }
}
The following is my pom.xml
<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.treocht.hibernate.tutorial</groupId>
<artifactId>hibernate-tutorial</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>First Hibernate Tutorial</name>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.7</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.2.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.0.beta9a</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.13</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<!--
we dont want the version to be part of the generated war file name
-->
<finalName>${artifactId}</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
And I have this META-INF/persistence.xml file:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd"
version="1.0">
<persistence-unit name="hello-world" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.foo.Message</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/my_db" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.password" value="password" />
<property name="hibernate.connection.username" value="username" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
You're indeed using incompatible versions of Hibernate artifacts as this can be verified using the official Hibernate Compatibility Matrix. Don't rely on some random tutorial found around the net for that.
But since you're using Maven, you actually don't need to declare all Hibernate artifacts, just leverage the transitive dependencies. So just declare a dependency in the hibernate-entitymanager (especially if you're not sure of what you're doing):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.4.0.GA</version><!-- for JPA 1.0 -->
</dependency>
And remove these hibernate, hibernate-core, hibernate-annotations, persistence-api, slf4j dependencies.
And if you want to change the version of the sfl4j-api artifact that you get transitively, you should do that in the dependency management section:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
</dependencyManagement>
Actually (and I'm sorry to say so) your whole pom is a big mess, try to spend some time cleaning it. Use mvn dependency:tree (or some visual fronted offered by your IDE) to do so.
And let me insist, don't rely on some random (and wrong) tutorial found around the net, leverage Maven transitive dependency mechanism.
PS: As of Hibernate 3.5, the various projects (Hibernate Annotation, Hibernate EntityManager) have been merged back to Hibernate Core and their versions are synchronized which simplifies a lot version management, even for Maven users.
There might be the conflicts in version.
compare it with this
This is now working, and my pom.xml looks like this:
<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.company.hibernate.tutorial</groupId>
<artifactId>hibernate-tutorial</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Hibernate Tutorial</name>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.com/maven2/</url>
</repository>
</repositories>
<dependencies>
<!-- Hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.4.0.GA</version><!-- for JPA 1.0 -->
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.13</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.6.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>