当前位置: 首页 > 知识库问答 >
问题:

无法获取当前线程的事务同步会话-Hibernate-spring

闻人弘雅
2023-03-14

同样的问题已经被问了很多次了,但是请在重复之前仔细阅读我的问题。

我不想使用基于注释的事务管理,所以我的问题与这里提出的问题不同。

我的XML声明

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:/comp::/env/jdbc/DS</value>
        </property>
    </bean>

    <!-- Create SessionFactory , one instance per application only -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <property name="dataSource" ref="dataSource"></property>

        <!-- Just for Testing Purpose -->
        <property name="mappingResources">
            <list>
                <value>com/mycompany/hbmapping/platform/support/Currency.hbm.xml</value>
            </list>
        </property>


        <!-- <property name="mappingDirectoryLocations"> <value>/WEB-INF/classes/com/mycompany/hbmapping</value> 
            </property> -->


        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.use_sql_comments">true</prop>
                <!-- Cache related properties -->
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory
                </prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>
                <prop key="hibernate.cache.use_structured_entries">true</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTxManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>

遵循作为bean的DAO声明

<bean id="currency" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="proxyInterfaces">
            <value>
                com.mycompany.dao.platform.support.CurrencyDao
            </value>
        </property>
        <property name="target">
            <ref bean="currencyTarget" />
        </property>
    </bean>

    <bean id="currencyTarget"
        class="com.mycompany.dao.platform.support.CurrencyDaoImpl">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>

我的TX建议

<tx:advice id="txAdvice" transaction-manager="hibernateTxManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"></tx:method>
            <tx:method name="update*" propagation="REQUIRED"></tx:method>
            <tx:method name="delete*" propagation="REQUIRED"></tx:method>
        </tx:attributes>
    </tx:advice>

AOP配置

<aop:config>


        <aop:pointcut
            expression="within(com.mycompany.dao.platform.support.CurrencyDao)"
            id="currencyPointCut" />

    </aop:config>

    <!-- applying advice on joint point -->
    <aop:config>



        <aop:advisor advice-ref="txAdvice" pointcut-ref="currencyPointCut" />
    </aop:config>

我的刀

public class CurrencyDaoImpl extends BaseBusinessDao implements CurrencyDao {

    /**
     * 
     */
    public CurrencyDaoImpl() {

    }

    public Serializable save(CurrencyModel currency) {

        Session session = getCurrentSession();

        Serializable id = session.save(currency);

        return id;
    }

    public void update(CurrencyModel currency) {

        Session session = getCurrentSession();

        session.update(currency);

    }

    public void delete(Serializable id) {

        Session session = getCurrentSession();

        session.delete(id);

    }
}

我的模型

public class CurrencyModel extends BaseModel {

    /**
     * 
     */
    private static final long serialVersionUID = 6543232156842168468L;

    private String currencyId;

    /**
     * name of the currency.
     */
    private String currency;

    private String trId;

    /**
     * 
     */
    public CurrencyModel() {

    }

    public String getCurrencyId() {
        return currencyId;
    }

    public void setCurrencyId(String currencyId) {
        this.currencyId = currencyId;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public String getTrId() {
        return trId;
    }

    public void setTrId(String trId) {
        this.trId = trId;
    }

    @Override
    public int hashCode() {

        return currency.hashCode();
    }

    @Override
    public boolean equals(Object obj) {

        if (obj == null) {
            return false;
        }

        if (!this.getClass().equals(obj.getClass())) {
            return false;
        }

        String anotherCurrency = ((CurrencyModel) obj).getCurrency();

        if (getCurrency().equals(anotherCurrency)) {
            return true;
        }

        return false;
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();

        sb.append("Currency for this instance is " + getCurrency());

        return sb.toString();
    }

}

我的Hibernate映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.mycompany.model.platform.support">
    <class name="CurrencyModel" table="tblcurrency">
        <id name="currencyId" column="currencyId">
            <generator class="uuid"></generator>
        </id>
        <version name="version" column="version" type="long"></version>
        <property name="rowStatus" column="rowStatus" not-null="true"></property>
        <property name="currency" column="currency" not-null="true"></property>

        <!-- this property needs to be replaces with transaction management root
             object UserTransactionModel
         -->    
         <property name="trId" not-null="true"></property>
    </class>
</hibernate-mapping>    

当我通过以下代码以编程方式运行此应用程序时,

SimpleNamingContextBuilder scb = new SimpleNamingContextBuilder();

        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://url:3306/db");
        ds.setUsername("dtsnuser");
        ds.setPassword("0okmnji9");
        ds.setValidationQuery("select 1");
        ds.setInitialSize(10);
        ds.setMaxActive(20);
        ds.setMaxIdle(10);
        ds.setMaxWait(-1);

        scb.bind("java:/comp::/env/jdbc/DS", ds);
        scb.activate();

        // setup bean factory
        dlBeanFactory = new DefaultListableBeanFactory();

        XmlBeanDefinitionReader xbl = new XmlBeanDefinitionReader(dlBeanFactory);
        xbl.loadBeanDefinitions(new FileSystemResource(
                "src/main/webapp/WEB-INF/app-config/applicationContext.xml"));



        currencyDao = (CurrencyDaoImpl) dlBeanFactory.getBean("currencyTarget");

        currencyModel = new CurrencyModel();
        currencyModel.setCurrency("INR");
        id = UUID.randomUUID().toString();
        currencyModel.setCurrencyId(id);

        String trId = UUID.randomUUID().toString();
        currencyModel.setTrId(trId);

它会抛出以下异常

org.hibernate.hibernateException:无法在org.springframework.orm.hibernate4.springsessioncontext.currentsession(springsessioncontext.java:134)在org.hibernate.internal.sessionfactoryimpl.getcurrentsession(springsessioncontext.java:990)在com.mycompany.dao.base.basebusinessdao.getcurrentsession(sessionfactoryimpl.java:990)在tect(TestResult.Java:106)在junit.framework.testResult.RunProtect(testResult.Java:124)在junit.framework.testCase.run(TestResult.Java:109)在junit.framework.testCase.run(TestCase.Java:118)在junit.framework.testSuite.runTest(TestSuite.Java:208)在junit.framework.testSuite.run(TestSuite.Java:203)在

我的数据源位于远程服务器上。

我做错了什么?忠告是否应用不当?我能发现这个建议是正确的吗?

请不要建议我使用基于注释的方法,我暂时不能使用它。

谢谢米希尔

共有1个答案

高胜
2023-03-14

在web应用程序中,这是使用aop处理事务的方法,

import javax.persistence.EntityManager;

    public final class JPAUtil {

        private static final ThreadLocal<EntityManager> currentEntityManager= new ThreadLocal<EntityManager>();
        private EntityManagerFactory entityManagerFactory;
        /**
         * Get the EntityManager for specified persistence unit for this thread.
         */
          public EntityManager em(String persistenceName) {
           EntityManager entityManager = null;
            if(entityManagerFactory != null) {
                EntityManager entityManager = entityManagerFactory.createEntityManager();
            bindForCurrentThread(entityManager);
            }
            return entityManager;
        }

        /**
         * Get the default EntityManager for this thread.
         */
        public static final EntityManager em() {
            EntityManager em = currentEntityManager.get();
            if (jpaPlugin == null || em == null) {
                return em(END_USER);
            }
            return em;
        }

        /**
         * Bind an EntityManager to the current thread.
         */
        public static final void bindForCurrentThread(EntityManager em) {
            currentEntityManager.set(em);
        }

        public static final void closeEM() {
            Logger.debug("Closing entity manager...");
            EntityManager em = currentEntityManager.get();
            if (em != null && em.isOpen()) {
                em.close();
            }
            Logger.debug("Entity manager closed successfully.");
            bindForCurrentThread(null);
        }

        public static final void beginTransaction() {
            em().getTransaction().begin();
        }

        public static final void commitTransaction() {
            em().getTransaction().commit();
        }

    }


        @Aspect
        public class DBAspects {

            private static final String READONLY_CONNECTION = "org.hibernate.readOnly";

            /**
             * Injecting entity manager before calling the em() method of JPABaseDAO. 
             * @param joinPoint
             * @param bd
             */
            @Before("call(* com.xo.web.models.dao.JPABaseDAO+.em(..)) && this(bd)")
            public void injectEntityManager(JoinPoint joinPoint, JPABaseDAO bd) {
                bd.setEntityManager(JPAUtil.em());
                //Logger.info("Injected enitymanager to : " + joinPoint.getSignature().getName());
            }

            /**
             * Pointcuts to get the XODBTransaction methods
             */
            @Pointcut("execution(@com.xo.web.persistence.XODBTransaction * *(..)) || call(public play.mvc.Result com.xo.web.controllers.*.*(..))")
            public void getTransactionMethods(){

            }

            /**
             * Pointcuts to get the XODBTransaction methods
             */
            @Pointcut("execution(@com.xo.web.persistence.XODBReadOnly * *(..))")
            public void getReadOnlyTransactionMethods(){

            }

            /**
             * Processing the transactions based on the XODBTransaction annotation.
             * @param joinPoint
             * @return
             * @throws Throwable
             */
            @Around("getTransactionMethods()")
            public Object handleTransaction(ProceedingJoinPoint joinPoint) {
                Object resultObject = null;
                EntityManager entityManager = JPAUtil.em();
                try{
                    if(entityManager != null) {
                        javax.persistence.EntityTransaction transaction = entityManager.getTransaction();
                        try{
                            final String callerName = joinPoint.getSignature().getName();
                            if(transaction != null && !transaction.isActive()) {
                                transaction.begin();
                                Logger.info("Transaction started for : " + callerName);
                            }
                            resultObject = joinPoint.proceed();
                            if(transaction != null && transaction.isActive()) {
                                transaction.commit();
                                Logger.info("Transaction ended for : " + callerName);
                            }
                        }catch(Throwable th) {
                            if(transaction != null && transaction.isActive()) {
                                transaction.rollback();
                            }
                            Logger.info("Error while performing CUD operation...", th);
                        }
                    }
                } catch(Throwable th) {
                    Logger.info("Error occurred while processing the request.", th); 
                } finally {
                    JPAUtil.closeEM();
                }
                Signature sig = joinPoint.getSignature();
                if (sig instanceof MethodSignature) {
                    Method method = ((MethodSignature) sig).getMethod();
                    if(method.getReturnType() == Result.class) {
                        Context.current().session().clear();
                    }
                }
                return resultObject;
            }
        }

希望这能给出一个思路。

 类似资料:
  • 问题内容: 我使用spring + hibernate创建了一个应用程序,但始终会收到此错误。这是我第一个使用hibernate的应用程序,我阅读了一些指南,但无法解决此问题。我在哪里做错了? 这是我的应用程序的代码 student.java studentDAO.java StudentDAOImpl.java MainApp.java springConfig.xml sql 问题答案: 你必

  • 我用spring+hibernate创建了一个应用程序,但总是得到这个错误。这是我使用hibernate的第一个应用程序,我读了一些指南,但我不能解决这个问题。我哪里做错了? 这是我的应用程序的代码 student.java StudentDAO.java StudentDAOImpl.java MainApp.java SpringConfig.xml SQL

  • 问题内容: 我从xml-转换为Java-Config的Spring4 / Hibernate4项目遇到以下异常。 该项目在Eclipse中启动了属性并且没有错误,但是在第一个请求出现Exception时。在我-class我已经配置为,,,。 我所有的服务都标有。 知道这可能来自哪里吗? 编辑1 根据要求,这里是堆栈跟踪: 编辑2 奇怪的是,我从另一个项目中完美地借用了整个Java-Config代码

  • 我将一个Spring4/Hibernate4项目从xml-config转换为Java-config时遇到以下异常。 项目在Eclipse中启动upproperty和errorfree,但在第一个请求时出现异常。在我的类中,我为、、、配置了。 我的所有服务都用注释。 知道这是从哪来的吗? 编辑%1 根据要求,这里的StackTrace: 编辑2 奇怪的是,我从另一个工作完美无缺的项目中借用了整个Ja

  • 问题内容: 我收到错误消息: 主要 @Service(“ productPartService”) @Repository(“ productPartDAO”) 如何解决? 更新: 如果我修改这样的方法: 它返回: 但是,如果我删除它最终会出现异常: 我可以通过添加来使它工作,但现在虽然链接到了,但我还是可以。如何解决? 问题答案: 错误表明没有名称为的实体。解决此问题的一种方法是将对象传递给方法

  • 我对spring、hibernate和数据库都是新手。我收到“HibernateException:无法获取当前线程的事务同步会话”错误。请帮帮我.找到下面的代码。 这是控制器 这是EntityDaoImplementation 这是我的模特课 这是服务实现 这是ProductTable.jsp 这是web.xml null 这是Dispatcher servlet 这是ApplicationCo