以下內容轉載於
在此權作爲筆記
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);