spring data事务
事务在spring data中的使用
1:事务一般在service层。因为一个service方法可能会多次调用不同的dao,为了保证事务的完整性,那么多次的dao都放到一个方法里面
2:读的时候可以不要事务,但是修改数据库的信息一定需要事务
3:@Query、@Modifying、@Transactional的综合使用
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.imooc</groupId> <artifactId>springdata</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--MySQL Driver--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> <!--spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.5.RELEASE</version> </dependency> <!--spring data jpa--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.8.0.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.6.Final</version> </dependency> </dependencies> </project>
com.gx.entity.User
package com.gx.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /* * 这个Entity的注解会告诉配置文件这是一个实体类 * 配置文件会根据EntityManagerFactory来判断是否有这个表 * 如果没有回字段生成 */ @Entity public class User { /*最好使用封装之后的类型 * */ private Integer id; private String name; private Integer age; @GeneratedValue//这个注解是告诉配置文件这个id是自增的 @Id//这个注解是告诉配置文件这是一个id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } /*这个注解是设置表user里面的name字段的长度为20,默认不为空 * 如果不设置的话默认是255 */ @Column(length=20,nullable=false) public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
com.gx.repository.UserRepository
package com.gx.repository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.RepositoryDefinition; import org.springframework.data.repository.query.Param; import com.gx.entity.User; @RepositoryDefinition(domainClass = User.class, idClass = Integer.class) public interface UserRepository{ /*根据用户id更新用户年龄 * @Modifying 允许修改 */ @Modifying @Query("update User u set u.age = :age where u.id = :id") public void update(@Param("id")Integer id,@Param("age")Integer age); }
配置文件spring-data-beans.xml
<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" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="username" value="root" /> <property name="password" value="root" /> <property name="url" value="jdbc:mysql://localhost:3307/test" /> </bean> <!-- 配置EntityManagerFactory --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 设置jpa适配器 --> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/> </property> <!-- 采用注解的方式,扫描包下面的java类 --> <property name="packagesToScan" value="com.gx"/> <!-- jpa的相关配置 --> <property name="jpaProperties"> <props> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop><!--执行的时候是否显示SQL--> <prop key="hibernate.format_sql">true</prop><!--执行的时候SQL是否格式化--> <prop key="hibernate.hbm2ddl.auto">update</prop><!--如果没有是否创建--> </props> </property> </bean> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <!--配置支持注解的事务--> <tx:annotation-driven transaction-manager="transactionManager"/> <!--配置spring data 需要扫描的包--> <jpa:repositories base-package="com.gx" entity-manager-factory-ref="entityManagerFactory"/> <!--在这个配置里面的内容spring都能够自动找到,更方便--> <context:component-scan base-package="com.gx"/> </beans>
com.gx.service.UserService
package com.gx.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gx.repository.UserRepository; @Service public class UserService { /*自动将UserRepository注入进来 *前提是spring-data-beans.xml里面有: * *<!--在这个配置里面的内容spring都能够自动找到,更方便--> *<context:component-scan base-package="com.gx"/> */ @Autowired private UserRepository userRepository;
@Transactional public void updateUser(Integer id,Integer age){ userRepository.update(id, age); } }
创建测试类com.gx.service.test.ServiceUserTest
package com.gx.service.test; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.gx.service.UserService; public class ServiceUserTest { //获取上下文 private ApplicationContext ctx = null; private UserService userService = null; @Before public void setup(){ System.out.println("setup is working......"); ctx = new ClassPathXmlApplicationContext("spring-data-beans.xml"); userService = ctx.getBean(UserService.class); } @After public void destory(){ ctx = null; System.out.println("destory is working......"); } @Test public void testUpdate(){ userService.updateUser(1, 55); } }
测试结果