配置基本属性 在application.properties里配置数据源和jpa的相关属性
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true
定义映射实体类
定义Controller类
@RestControllerpublic class PersonCtroller {
@Autowired PersonServer personServer;
@RequestMapping("/rollback")
public Person rollback(Person person){
return personServer.savePersonWithRollBack(person);
}
@RequestMapping("/norollback")
public Person noRollback(Person person){
return personServer.savePersonWithOutRollBack(person);
}
}
定义数据访问层
public interface PersonRepository extends JpaRepository
定义Server层
@Servicepublic class PersonServerImp implements PersonServer {
@Autowired
PersonRepository personRepository;
@Transactional(rollbackFor = {IllegalArgumentException.class})
@Override
public Person savePersonWithRollBack(Person person) {
Person p = personRepository.save(person);
if (p.getName().equals("xxx")){
throw new IllegalArgumentException("用户已存在,数据会回滚");
}
return p;
}
}