开发者社区> 问答> 正文

javax.persistence.TransactionRequiredExc?报错

想搭建下spring+hibernate最小系统,测试时报错,指导下

spring-test-dao.xml

<!-- <context:annotation-config/>可以识别@Autowired@PersisitenceContext等注解,那<context:componet-scan base-package>在指定包里除了可以识别上面<context:annotation-config>的功能外,还可以识别它过滤的注解 -->
	<context:component-scan base-package="com.suntopo.dao" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
	</context:component-scan>

	<context:property-placeholder location="classpath:resources.properties"/>


        
	<!-- jpa Entity Factory 配置 -->
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSourceProxy" />
		<property name="packagesToScan" value="com.suntopo.model" /><!-- 扫描包@Entity -->
        <property name="persistenceProvider">
            <bean class="org.hibernate.ejb.HibernatePersistence"/>
        </property>
		<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />

	</bean>

	<!-- 指定hibernate为jpa的厂商适配器 -->
	<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
		<property name="generateDdl" value="false" />
		<property name="database" value="${jpa.database}" />
		<property name="databasePlatform" value="${jpa.databasePlatform}" />
		<property name="showSql" value="${jpa.showSql}" />
	</bean>

	<!-- 数据源代理对象,数据源对象被代理后就具有了事务上下文感知的能力 -->
	<bean id="dataSourceProxy" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
		<property name="targetDataSource" ref="dataSource" />
	</bean>

	<!-- 数据源 -->
	<!--see https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_DruidDataSource%E5%8F%82%E8%80%83%E9%85%8D%E7%BD%AE -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="url" value="${connection.url}" />
		<property name="username" value="${connection.username}" />
		<property name="password" value="${connection.password}" />
		<!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass 
		<property name="driverClassName" value="${connection.driver}" />-->

		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="${druid.initialSize}" />
		<property name="minIdle" value="${druid.minIdle}" />
		<property name="maxActive" value="${druid.maxActive}" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="${druid.maxWait}" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />

		<property name="validationQuery" value="${druid.validationQuery}" />
		<property name="testWhileIdle" value="${druid.testWhileIdle}" />
		<property name="testOnBorrow" value="${druid.testOnBorrow}" />
		<property name="testOnReturn" value="${druid.testOnReturn}" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。 -->
		<property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
		<property name="maxPoolPreparedStatementPerConnectionSize"
			value="${druid.maxPoolPreparedStatementPerConnectionSize}" />

		<!-- 配置监控统计拦截的filters 
		<property name="filters" value="${druid.filters}" />-->

	</bean>
	
	<!--事务管理器配置-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    
    	<!-- 配置 Annotation 驱动,定义事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
一个简易的实体
@Entity
@Table(name = "pc_user")
public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer id;
	private String name;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
一个简易的保存
@Repository
public class HibernateCURD {

	@PersistenceContext
    private EntityManager entityManager;
	
	
	public void save(User user) {
		entityManager.persist(user);
	}
}
测试下
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-test-dao.xml"})
public class SaveTest {

	@Autowired
	private HibernateCURD hibernateCURD;
	
	@Test
	public void save() {
		User user = new User();
		user.setName("saveTest");
		
		//HibernateCURD hibernateCURD= new HibernateCURD();
		
		hibernateCURD.save(user);
		
	}
}

报错:

解决了亲,开始看报错以为是没有EnityManager,应该是没有entityManager没有加事务,只需要在持久化操作上加@Transactional就可以了

@Repository
@Transactional
public class HibernateCURD {

	@PersistenceContext
    private EntityManager entityManager;
	
	
	public void save(User user) {
		entityManager.persist(user);
	}
	
}
<p>
	<br>
</p>
<p>
	<br>
</p>

展开
收起
爱吃鱼的程序员 2020-06-14 17:22:04 843 0
1 条回答
写回答
取消 提交回答
  • 加@Transactional就可以了

    2020-06-23 17:12:29
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载