<!--数据库相关配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
步骤二:在application.properties配置文件中加入数据库的相关配置,配置信息如下所示。
spring.datasource.url = jdbc:mysql://localhost:3306/webtest
spring.datasource.username = root
spring.datasource.password = 220316
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dial
新建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 {
@AutowiredPersonServer 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
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)