Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 即使我在hibernate中不使用@transactional,事务也会被提交_Spring_Hibernate_Jpa - Fatal编程技术网

Spring 即使我在hibernate中不使用@transactional,事务也会被提交

Spring 即使我在hibernate中不使用@transactional,事务也会被提交,spring,hibernate,jpa,Spring,Hibernate,Jpa,我正在尝试将spring与hibernate集成,并尝试在dao层中使用会话工厂 我的测试类如下所示: package com.transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXm

我正在尝试将spring与hibernate集成,并尝试在dao层中使用会话工厂 我的测试类如下所示:

package com.transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.transactionManagement.java.Employee;
import com.transactionService.service.TransactionService;

public class TransactionManagementTest {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new  ClassPathXmlApplicationContext("Bean.xml");
        Employee emp = (Employee)applicationContext.getBean("employee");
        emp.setFirstName("vivek3");
        emp.setLastName("krishna2");
        emp.setAmount(2000);
        TransactionService ts=(TransactionService) applicationContext.getBean("transactionService");
        ts.insertEmployee(emp);
    }

}
我创建了服务和dao接口 道: 包com.Transaction.dao

import com.transactionManagement.java.Employee;

public interface Transaction {

    public void insertEmployee(Employee emp);

    public Employee getEmployeebyId(Integer employeeIdentifier);

    public int updateSalaryfoeEmployee(Integer employeeIdentifier,Integer Salary);

}
服务:

package com.transactionService.service;

import com.transactionManagement.java.Employee;

public interface TransactionService {

    public void insertEmployee(Employee emp);

    public Employee getEmployeebyId(Integer employeeIdentifier);

    public int updateSalaryfoeEmployee(Integer employeeIdentifier,Integer Salary);

}
相应的dao和服务impl:

package com.Transaction.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.Transaction.dao.Transaction;
import com.transactionManagement.java.Employee;

@Component("transactionDao")
public class TransactionDaoImpl implements Transaction {

    @Autowired
    private Employee employee;

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Autowired
    private SessionFactory sessionFactory;


    public void insertEmployee(Employee emp) {
        sessionFactory.openSession().save(emp);

    }

    public Employee getEmployeebyId(Integer employeeIdentifier) {
        // TODO Auto-generated method stub
        return (Employee) sessionFactory.openSession().get(Employee.class, employeeIdentifier);
    }

    public int updateSalaryfoeEmployee(Integer employeeIdentifier,
            Integer Salary) {
        // TODO Auto-generated method stub
        Query q= (Query) sessionFactory.openSession().createQuery("update Employee set Salary=:salary where id=:id")
                .setParameter("salary", Salary)
                .setParameter("id", employeeIdentifier);
        return q.executeUpdate();

    }

}
package com.transactionService.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.Transaction.dao.Transaction;
import com.transactionManagement.java.Employee;
import com.transactionService.service.TransactionService;


@Component("transactionService")
public class TransactionServiceImpl implements TransactionService{

    @Autowired
    private Transaction transactionDao;

    public void insertEmployee(Employee emp) {
        transactionDao.insertEmployee(emp);

    }

    public Employee getEmployeebyId(Integer employeeIdentifier) {

        return transactionDao.getEmployeebyId(employeeIdentifier);
    }

    public int updateSalaryfoeEmployee(Integer employeeIdentifier,
            Integer Salary) {
        return transactionDao.updateSalaryfoeEmployee(employeeIdentifier, Salary);
    }

}
服务impl:

package com.Transaction.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.Transaction.dao.Transaction;
import com.transactionManagement.java.Employee;

@Component("transactionDao")
public class TransactionDaoImpl implements Transaction {

    @Autowired
    private Employee employee;

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Autowired
    private SessionFactory sessionFactory;


    public void insertEmployee(Employee emp) {
        sessionFactory.openSession().save(emp);

    }

    public Employee getEmployeebyId(Integer employeeIdentifier) {
        // TODO Auto-generated method stub
        return (Employee) sessionFactory.openSession().get(Employee.class, employeeIdentifier);
    }

    public int updateSalaryfoeEmployee(Integer employeeIdentifier,
            Integer Salary) {
        // TODO Auto-generated method stub
        Query q= (Query) sessionFactory.openSession().createQuery("update Employee set Salary=:salary where id=:id")
                .setParameter("salary", Salary)
                .setParameter("id", employeeIdentifier);
        return q.executeUpdate();

    }

}
package com.transactionService.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.Transaction.dao.Transaction;
import com.transactionManagement.java.Employee;
import com.transactionService.service.TransactionService;


@Component("transactionService")
public class TransactionServiceImpl implements TransactionService{

    @Autowired
    private Transaction transactionDao;

    public void insertEmployee(Employee emp) {
        transactionDao.insertEmployee(emp);

    }

    public Employee getEmployeebyId(Integer employeeIdentifier) {

        return transactionDao.getEmployeebyId(employeeIdentifier);
    }

    public int updateSalaryfoeEmployee(Integer employeeIdentifier,
            Integer Salary) {
        return transactionDao.updateSalaryfoeEmployee(employeeIdentifier, Salary);
    }

}
对应的Beans.xml:

<?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:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring 
        http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

 <import resource="DataSource.xml"/>

 <context:component-scan base-package="com.Transaction.dao"></context:component-scan>
 <context:component-scan base-package="com.Transaction.dao.impl"></context:component-scan>
 <context:component-scan base-package="com.transactionService.service"></context:component-scan>
 <context:component-scan base-package="com.transactionService.service.impl"></context:component-scan>
 <context:component-scan base-package="com.transactionManagement.java" />

 <bean id="employee" class="com.transactionManagement.java.Employee"></bean>
 <bean id="transactionDao" class="com.Transaction.dao.impl.TransactionDaoImpl">
 <property name="employee" ref="employee"></property>
 <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>

 <bean id="springTransactionTest" class="com.transaction.SpringTransactionManageTest">
 </bean>
 <bean id="sessionFactory"
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

    <property name="dataSource"><ref bean="dataSource"/>
    </property>
    <property name="packagesToScan" value="com.transactionManagement.java" />

    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
     </property>

    </bean>

    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

org.hibernate.dialogue.sqlserverdialogue
真的
数据源文件:

<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean id="dataSource"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
    <property name="url" value="jdbc:jtds:sqlserver://PRAMOD-LAPTOP;databaseName=TestMart1;" />
    <property name="username" value="sa" />
    <property name="password" value="1234" />
</bean>

</beans>

输出跟踪:

Mar 05, 2017 1:20:37 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@25f38edc: startup date [Sun Mar 05 13:20:37 IST 2017]; root of context hierarchy
Mar 05, 2017 1:20:37 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Bean.xml]
Mar 05, 2017 1:20:38 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [DataSource.xml]
Mar 05, 2017 1:20:38 PM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'transactionDao': replacing [Generic bean: class [com.Transaction.dao.impl.TransactionDaoImpl]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [F:\Bhaskar\SpringTransactionManagement\target\classes\com\Transaction\dao\impl\TransactionDaoImpl.class]] with [Generic bean: class [com.Transaction.dao.impl.TransactionDaoImpl]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [Bean.xml]]
Mar 05, 2017 1:20:38 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@490ab905: defining beans [dataSource,transactionDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,transactionService,employee,springTransactionTest,sessionFactory,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Mar 05, 2017 1:20:38 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: net.sourceforge.jtds.jdbc.Driver
Mar 05, 2017 1:20:39 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Mar 05, 2017 1:20:39 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.18.Final}
Mar 05, 2017 1:20:39 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 05, 2017 1:20:39 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 05, 2017 1:20:40 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Mar 05, 2017 1:20:40 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Mar 05, 2017 1:20:40 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 05, 2017 1:20:40 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into Employee (amount, first_name, last_name) values (?, ?, ?)
2017年3月5日下午1:20:37 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息:刷新org.springframework.context.support。ClassPathXmlApplicationContext@25f38edc:启动日期[2017年3月5日星期日13:20:37];上下文层次结构的根
2017年3月5日下午1:20:37 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息:从类路径资源[bean.XML]加载XMLBean定义
2017年3月5日下午1:20:38 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息:从类路径资源[DataSource.XML]加载XMLbean定义
2017年3月5日下午1:20:38 org.springframework.beans.factory.support.DefaultListableBeanFactory注册表BeanDefinition
信息:覆盖bean“transactionDao”的bean定义:替换[genericbean:class[com.Transaction.dao.impl.TransactionDaoImpl];scope=singleton;abstract=false;lazyInit=false;autowireMode=0;dependencyCheck=0;autowireCandidate=true;primary=false;factoryBeanName=null;factoryMethodName=null;initMethodName=null;destroyMethodName=null;在文件[F:\Bhaskar\SpringTransactionManagement\target\classes\com\Transaction\dao\impl\TransactionDAImpl.class]]中定义,带有[genericbean:class[com.Transaction.dao.impl.TransactionDaoImpl];scope=;abstract=false;lazyInit=false;autowireMode=0;dependencyCheck=0;autowireCandidate=true;primary=false;factoryBeanName=null;factoryMethodName=null;initMethodName=null;在类路径资源[bean.xml]中定义]
2017年3月5日下午1:20:38 org.springframework.beans.factory.support.DefaultListableBeanFactory预实例化单例
信息:在org.springframework.beans.factory.support中预实例化单例。DefaultListableBeanFactory@490ab905:定义bean[数据源,transactionDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.annotationk、 context.annotation.internalPersistenceAnnotationProcessor、transactionService、employee、springTransactionTest、sessionFactory、transactionManager、org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor];工厂层次结构的根
2017年3月5日下午1:20:38 org.springframework.jdbc.datasource.drivermanager数据源setdrivercassname
信息:加载的JDBC驱动程序:net.sourceforge.jtds.JDBC.driver
2017年3月5日下午1:20:39 org.hibernate.annotations.common.Version
信息:HCANN000001:Hibernate Commons注释{4.0.2.Final}
2017年3月5日下午1:20:39 org.hibernate.Version日志版本
信息:hh000412:Hibernate核心{4.2.18.Final}
2017年3月5日下午1:20:39 org.hibernate.cfg.Environment
信息:HH000206:找不到hibernate.properties
2017年3月5日下午1:20:39 org.hibernate.cfg.Environment buildBytecodeProvider
信息:HH000021:字节码提供程序名称:javassist
2017年3月5日下午1:20:40 org.hibernate.dialogue.dialogue
信息:HH000400:使用方言:org.hibernate.dialogue.sqlserverdialogue
2017年3月5日下午1:20:40 org.hibernate.engine.jdbc.internal.LobCreatorBuilder UseContexturationAllobCreation
信息:HH000423:禁用上下文LOB创建,因为JDBC驱动程序报告JDBC版本[3]小于4
2017年3月5日下午1:20:40 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
信息:HH000399:使用默认事务策略(直接JDBC事务)
2017年3月5日下午1:20:40 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
信息:HH000397:使用ASTQueryTranslatorFactory
Hibernate:在员工(金额、名字、姓氏)中插入值(?、、?)
问题:我没有使用@transactional,但仍然在进行插入。有人能解释一下吗

问候,,
Bhaskar

如果您在ts.insertEmployee(emp)之后抛出Exception;…它会回滚吗?您的设置在许多方面都有缺陷,这可能是因为您的连接上有自动提交。但是,正如前面所述,您的设置有缺陷,您使用的是
openSession
,而没有正确管理会话(或事务)这将导致连接泄漏(在某些情况下,您的应用程序将死亡,因为您的数据库不允许再进行连接)。接下来,即使您使用了正确的方法,由于使用了错误的事务管理器,它仍然是错误的(您应该使用的是
HibernateTransactionManager
,而不是
DataSourceTransactionManager