spring boot怎么初始化连接数据库
1个回答
展开全部
新建Spring Boot项目,依赖选择JPA(spring-boot-starter-data-jpa)和Web(spring-bootstarter-web)。
配置基本属性 在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<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;
}
}
配置基本属性 在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<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;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询