以下内容转载于
在此权作为笔记
Spring事务管理
1. 首先,我们先在Spring配置文件中开启事务管理
<!--3 配置事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--4 配置支持注解的事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
2. 编写dao层方法
/**
* 根据id修改年龄
* Modifying 该注解表示允许修改
* @param id
* @param age
*/
@Modifying
@Query("update Employee o set o.age=:age where o.id = :id")
public void update(@Param("id")Integer id, @Param("age")Integer age);
3. 编写Service层代码
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wzw.springdata.dao.EmployeeRepository2;
import com.wzw.springdata.dao.EmployeeRepository3;
import com.wzw.springdata.model.Employee;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository2 er2;
@Transactional
public void update(Integer id, Integer age) {
er2.update(id, age);
}
}
4. 编写测试代码
@Test
public void fun8() {
System.out.println("1: " + es);
es.update(2, 25);
}
5. @Modifying
@Modifying
@Query("update Employee o set o.age=:age where o.id = :id")
@Modifying注解表示可以修改
SpringData的CRUD
1. 创建CrudRepository接口的子接口
import org.springframework.data.repository.CrudRepository;
import com.wzw.springdata.model.Employee;
public interface EmployeeRepository3 extends CrudRepository<Employee, Integer>{
}
2. 编写service层方法
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wzw.springdata.dao.EmployeeRepository2;
import com.wzw.springdata.dao.EmployeeRepository3;
import com.wzw.springdata.model.Employee;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository3 er3;
@Transactional
public void save() {
Employee employee = new Employee();
employee.setName("test"+new SimpleDateFormat("yyyy").format(new Date()).toString());
employee.setAge(20);
er3.save(employee);
}
}
3. 编写测试方法
@Test
public void fun9() {
System.out.println("1: " + es);
es.save();
}
4. CrudRepository的主要方法
long count();
boolean exists(Integer arg0);
<S extends StudentPO> S save(S arg0);
<S extends StudentPO> Iterable<S> save(Iterable<S> arg0);
void delete(Integer arg0);
void delete(Iterable<? extends StudentPO> arg0);
void delete(StudentPO arg0);
void deleteAll();
StudentPO findOne(Integer arg0);
Iterable<StudentPO> findAll();
Iterable<StudentPO> findAll(Iterable<Integer> arg0);