SpringBoot连接MySql

 时间:2024-10-12 22:40:28

1、新建Spring Boot项目,依赖选择JPA(spring-boot-starter-data-jpa)和Web(spring-bootstarter-web)。

SpringBoot连接MySql

2、配置基本属性在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

SpringBoot连接MySql

3、定义映射实体类

SpringBoot连接MySql
SpringBoot连接MySql

4、定义Controller类@RestControllerpublic class PersonCtroller { @Autowir髫潋啜缅ed PersonServer personServer; @RequestMapping("/rollback") public Person rollback(Person person){ return personServer.savePersonWithRollBack(person); } @RequestMapping("/norollback") public Person noRollback(Person person){ return personServer.savePersonWithOutRollBack(person);}}

5、定义数据访问层public interface PersonRepository extends JpaRepository<Person, Long> {}

6、定义Server层@Servicepublic cla衡痕贤伎ss 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、浏览器访问

SpringBoot连接MySql
  • Microsoft Word 2010如何删除已有的页码
  • 神仙道乾坤套装材料大全 100级紫装材料掉落出处
  • 网址大全夜间模式亮度怎么调到最弱
  • 雨雪天气建筑施工需要注意什么
  • 热门搜索
    反对邪教的手抄报 关于热爱生命的手抄报 绿色校园手抄报内容 关于邪教的手抄报 诵读经典手抄报 手抄报的装饰花边 关于读书节的手抄报 安全手抄报版面设计图 科技节手抄报内容 a4手抄报版面设计图