SpringBoot连接MySql

2025-11-10 09:00:30

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.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

SpringBoot连接MySql

3、定义映射实体类

SpringBoot连接MySql

SpringBoot连接MySql

4、定义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); 

 }

}

5、定义数据访问层

public interface PersonRepository extends JpaRepository<Person, Long> {}

6、定义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、浏览器访问

SpringBoot连接MySql

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢