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瀏覽器訪問