相关文章推荐
淡定的松鼠  ·  mac 还原python环境路径 ...·  1 年前    · 
卖萌的充电器  ·  Python ...·  1 年前    · 
精明的蚂蚁  ·  c++读取xml配置-掘金·  1 年前    · 
文雅的椅子  ·  cocoapods 问题 总结 - 简书·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Any help will be greatly appreciated.

We are working on a web application. Which uses a JAR file (a java maven project) and has been added as a maven dependency in the web application. Combination of this JAR file and web application itself creating problem.

Both web application and JAR are using Hibernate JPA to interact with database. But both are using 2 different ways for creating/initializing entityManagerFactory.

Web Application uses Spring xml based configuration to initialize entityManagerFactory.

CODE: persistence.xml code:

<persistence-unit name="org.jbpm.persistence.jpa.local"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <mapping-file>META-INF/JBPMorm-JPA2.xml</mapping-file>
        <class>org.drools.persistence.info.SessionInfo</class>
        <class>org.jbpm.persistence.processinstance.ProcessInstanceInfo</class>
        <class>org.drools.persistence.info.WorkItemInfo</class>     
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
            <property name="hibernate.max_fetch_depth" value="3" />         
            <property name="hibernate.show_sql" value="true" />         
        </properties>
    </persistence-unit>

Spring configuration:

    <context:component-scan base-package="com.company.rd.core" />
    <context:component-scan base-package="com.company.rd.services" />
    <jee:jndi-lookup id="testDataSource" jndi-name="java:comp/env/jdbc/SybaseDB" />
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="testDataSource"/>
        <property name="defaultTimeout" value="120"></property>
    </bean>
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="org.jbpm.persistence.jpa.local" />
        <property name="dataSource" ref="testDataSource" />
        <property name="jpaDialect" ref="jpaDialect" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
    </bean>
    <bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    <bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
        <property name="jpaDialect" ref = "jpaDialect"></property>
        <property name="defaultTimeout" value="120"></property>
    </bean>
    <jee:jndi-lookup id="logDataSource" jndi-name="java:comp/env/jdbc/DRMLOG" />
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans> 

And Here is the code to initializing entitymanagerFactory in JAR file.

persistence.xml

<persistence-unit name="codeAuthorization" transaction-type="RESOURCE_LOCAL">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <non-jta-data-source>java:/comp/env/jdbc/SybaseDB</non-jta-data-source>
      <class>com.company.auth.entity.AuthorizationCode</class>
      <class>com.company.auth.entity.UserInvalidAttempt</class>
      <class>com.company.auth.entity.AuthorizationProperty</class>
        <properties>            
            <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>

And a java file which is injected into Base DAO through spring.

@Service
public class AuthorizationEntityMangerService {
    @PersistenceUnit(name = "codeAuthorization")
    private EntityManagerFactory entityManagerFactory;
    public AuthorizationEntityMangerService() {
        entityManagerFactory = Persistence
                .createEntityManagerFactory("org.jbpm.persistence.jpa.local");
    public EntityManagerFactory getEntityManagerFactory() {
        return entityManagerFactory;
    public EntityManager getEntityManager() {
        return this.entityManagerFactory.createEntityManager();
    public void closeEntityManager(EntityManager entityManager) {
        if (entityManager != null && entityManager.isOpen()) {
            entityManager.close();
    public EntityTransaction getTransaction(EntityManager entityManager) {
        return entityManager.getTransaction();
    public void rollBackTransaction(EntityTransaction transaction) {
        if (transaction != null && transaction.isActive()) {
            transaction.rollback();
    public void commitTransaction(EntityTransaction transaction) {
        if (transaction != null && transaction.isActive()) {
            transaction.commit();

Calling code from Base DAO.

public Object getSingleResult(final String queryString, final String key,
            final NamedQueryParameter namedQueryParameter) {
        EntityTransaction transaction = null;
        EntityManager entityManager = null;
        try {
            entityManager = this.entityMangerService.getEntityManager();
            transaction = entityMangerService.getTransaction(entityManager);
            transaction.begin();
            final Query query = entityManager.createQuery(queryString);
            setQueryParameter(query, namedQueryParameter);
            final Object result = query.getSingleResult();
            entityMangerService.commitTransaction(transaction);
            return result;
        } catch (final NoResultException e) {
            entityMangerService.rollBackTransaction(transaction);
            logger.error("Error" : " + e.getMessage());
            return null;
        } finally {
            entityMangerService.closeEntityManager(entityManager);

Now Here is the problem when ever line entityManager.createQuery(queryString); execute it throws the exception.

2015-06-05 17:39:46,363 WARN DefaultExceptionHandler:94 - Unhandled exception caught by the Stripes default exception handler. java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: AuthorizationProperty is not mapped [SELECT pe.value FROM AuthorizationProperty pe WHERE pe.name=:propertyName AND pe.deleted=0] at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1364) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300) at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke (ExtendedEntityManagerCreator.java:334) at com.sun.proxy.$Proxy53.createQuery(Unknown Source) at com.company.authentication.dao.AuthorizationBaseDAO.getSingleResult(AuthorizationBaseDAO.java:40) at com.company.authentication.dao.PropertyDAOImlp.getPropertyValue(PropertyDAOImlp.java:22) at com.company.authentication.services.AuthorizationPropertyService.getPropertyValueByName (AuthorizationPropertyService.java:19) at com.company.rd.servlet.JspAuthorizationRestFilter.hasAuthorizationCode (JspAuthorizationRestFilter.java:105) at com.company.rd.servlet.AbstractAuthorizationRestFilter.isRequestAuthenticated (AbstractAuthorizationRestFilter.java:120) at com.company.rd.servlet.JspAuthorizationRestFilter.doFilter(JspAuthorizationRestFilter.java:84)

I have debugged the code and found entityManagerFactory for persistenceUnit "codeAuthorization" is not initialized. Only "org.jbpm.persistence.jpa.local" is available (verified through eclipse debugger) inside this method.

Note: This JAR is working fine in some other application where web application and JAR using same way to initialize entityMangerFactory [through Persistence.createEntityManagerFactory("")].

Please let me know How can I get "codeAuthorization" entiryManagerFactory

You are using Spring then use Spring, currently you are doing a lot of work to work around Spring and dependency injection and managed transaction. Don't use Persistence.createEntityManagerFactory(""). Just inject the EntityManager where you need it using an EntityManager field annotated with @PersistenceContext and specify the name of the one you want.

Also don't manage the transactions, entity manager yourself, spring does that for you. For this use the right PlatformTransactionManager the JpaTransactionManager and not the DatasourceTransactionManager as that won't work in a JPA environment. (At least not to manage your JPA transactions).

Doing this will really simplify your code and your life.

So basically ditch the service that is doing those nasty things and simple do things like this in your dao.

@Repository
public class YourDao {
    @PersistenceContext(name="codeAuthorization")
    private EntityManager em;
    @Transactional
    public Object getSingleResult(final String queryString, final String key,
        final NamedQueryParameter namedQueryParameter) {
        final Query query = em.createQuery(queryString);
        setQueryParameter(query, namedQueryParameter);
        return query.getSingleResult();

In your configuration replace the DatasourceTransactionManager with the JpaTransactionManager and add <tx:annotation-driven />. Then clean your code.

Note: The JpaTransactionManager is perfectly capable of managing plain JDBC transactions if you still need those, ideally you would have a single transaction manager.

Thank Deinum for your suggestions. But I am not allowed to change a lot in this JAR code as I mentioned in my above post this is already working fine in more than one application(project). Although all those projects are not using spring configurations for entityManagerFactory creation. They all are just using Persistence.createEntityManagerFactory("persistenceUnitName") for entityManagerFactory. So this JAR is not creating problem there. – Shakir Jun 11, 2015 at 6:01 But I have managed to find a solution for this problem. In the service class AuthorizationEntityMangerService.java (source code above). I moved out the entityManagerFactory initialization code from constructor to a post construct method @PostConstruct public void postConstruct() { entityManagerFactory = Persistence .createEntityManagerFactory("codeAuthorization"); } Now its working fine. – Shakir Jun 11, 2015 at 6:06 You shouldn't have it in the constructor or @PostConstruct method. The bean is a singleton and each time the method is invoked you need to call this method. However I still shudder with the way your code is implemented, you are using a framework and try very hard not to use it. Also you don't have to change the jar you have to change your daos/repositories. – M. Deinum Jun 11, 2015 at 6:09

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.