boot怎么操作数据库?
新建Spring Boot项目,依赖选择JPA(spring-boot-starter-data-jpa)和Web(spring-bootstarter-web)。配置基本属性 在application.properties里配置数据源和jpa的相关属性spring.datasource.driverClassName=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/springbootspring.datasource.username=rootspring.datasource.password=123456spring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.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<Person, Long> {}定义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; } }7浏览器访问
Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有