springMVC 注解事务配置

项目使用的是SPRING MVC .我用注解声明事务。可是事务一直无效,可以查询,但是不能添加,改,删。以前用struts都可以,郁闷呐。今天网上查了一下终于搞好了。

首先jpa的persistence.xml


<?xml version="1.0" encoding="UTF-8"?>
<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
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
    
	<persistence-unit name="spring3" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<properties>
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/sony" />
			<property name="hibernate.connection.username" value="root" />
			<property name="hibernate.connection.password" value="123" />
			<property name="hibernate.max_fetch_depth" value="3"/>
       	   	    <property name="hibernate.hbm2ddl.auto" value="update"/>
	 	        <property name="hibernate.jdbc.fetch_size" value="18"/>
	   	        <property name="hibernate.jdbc.batch_size" value="10"/>
	  	        <property name="hibernate.show_sql" value="true"/>
	   	        <property name="hibernate.format_sql" value="true"/> 
	        </properties>
	</persistence-unit>

</persistence>

spring的,applicationContext.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:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
                  
  <context:annotation-config /> 
 <context:component-scan base-package="com.spring3">
<!--将Controller的注解排除掉 -->
   <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
 </context:component-scan>
  
  <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="spring3"/>
  </bean>  
  
<!--
 <bean id="userDao" class="com.spring3.dao.UserDaoImpl">
   <property name="entityManagerFactory" ref="entityManagerFactory"></property>
 </bean>
 -->
 

  <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    	<property name="entityManagerFactory" ref="entityManagerFactory"/>
  </bean>

  
 
  <tx:annotation-driven transaction-manager="transactionManager"/>
  
  
  
</beans>

spring 的mvc   example-servlet.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:p="http://www.springframework.org/schema/p" 
    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">

    <context:component-scan base-package="com.spring3">
    <!-- 将Service注解给去掉  -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>
   <context:annotation-config /> 


		<bean id="viewResolver"
			class="org.springframework.web.servlet.view.UrlBasedViewResolver">
			<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
			<property name="prefix" value="/"/>
			<property name="suffix" value=".jsp"/>
       </bean>
       
  </beans>

在业务类里加上@Transactional 就好


package com.spring3.dao;


import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.spring3.entity.User;


@Service
@Transactional
public class UserDaoImpl implements UserDao{
	
	@PersistenceContext protected EntityManager em;
	  
//	@Resource EntityManagerFactory entityManagerFactory;
	

	public User login(User user){
	//	EntityManager em=entityManagerFactory.createEntityManager();
		User u=null;
		Query query=em.createQuery("select u from User  u where username = '"+user.getUsername()+"'  and  password = '"+user.getPassword()+"'   ");
		try{
			 u = (User) query.getSingleResult();
			
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		return u; 
	 }

	@Override
	public void save(User user) {
		
		em.persist(user);
		
	}
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是通过注解配置Spring MVC的代码示例: ```java @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.example.controller"}) public class AppConfig implements WebMvcConfigurer { @Autowired private Environment env; @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/views/", ".jsp"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("db.driver")); dataSource.setUrl(env.getProperty("db.url")); dataSource.setUsername(env.getProperty("db.username")); dataSource.setPassword(env.getProperty("db.password")); return dataSource; } @Bean public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(dataSource()); } @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoggingInterceptor()); } } ``` 在上面的代码中,使用了注解配置Spring MVC,其中`@Configuration`表示这是一个配置类,`@EnableWebMvc`表示启用Spring MVC,`@ComponentScan`表示扫描指定包下的组件。 `WebMvcConfigurer`是Spring MVC的配置接口,我们可以在配置类中实现该接口来配置Spring MVC。 `configureViewResolvers`方法用于配置视图解析器,`addResourceHandlers`方法用于配置静态资源处理器,`configureDefaultServletHandling`方法用于启用默认的Servlet处理器。 `viewResolver`方法用于配置视图解析器,`dataSource`方法用于配置数据源,`jdbcTemplate`方法用于配置JdbcTemplate,`transactionManager`方法用于配置事务管理器。 `addInterceptors`方法用于配置拦截器。在上面的例子中,我们定义了一个`LoggingInterceptor`拦截器,并将其添加到拦截器列表中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值