第七章 使用JPA操作数据库
本章主要介绍如何在Spring Boot的Web应用中使用Mysq数据库,也充分展示Spring Boot的优势(尽可能少的代码和配置).
数据访问层我们将使用Spring Data JPA和Hibernate(JPA的实现之一).
Maven pom.xml文件
lightsword/pom.xml
在项目中增加如下依赖文件
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
配置文件application.properties
在src/main/resources/application.properties中设置数据源和jpa配置:
#mysql
spring.datasource.url = jdbc:mysql://localhost:3306/lightsword?useUnicode=true&characterEncoding=UTF8
spring.datasource.username = root
#root@localhost ::TZaMojg3ntd
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=0
spring.datasource.max-idle=0
spring.datasource.min-idle=0
spring.datasource.max-wait=10000
spring.datasource.max-wait-millis=31536000
# 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.dialect.MySQL5Dialect
全部的配置都在如上的文件中了,不需要另外的XML配置和Java配置。
上文中的数据库配置,你需要换成你的数据库的地址和用户名密码。
hibernate的ddl-auto=update配置表名,数据库的表和列会自动创建(根据Java实体类,在scala中,只要在实体类上标注@Entity,成员变量上标注@BeanProperty),这里 可以看到更多得hibernate配置。
实体类
创建一个HttpApi实体类,实体和Mysql数据库的http_api表相对应(这个表字段会在应用启动的时候,自动生成)。
package com.springboot.in.action.entity
import java.util.Date
import javax.persistence.{ Entity, GeneratedValue, GenerationType, Id }
import scala.language.implicitConversions
import scala.beans.BeanProperty
@Entity
class HttpApi {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@BeanProperty
var id: Integer = _
@BeanProperty
var httpSuiteId: Integer = _
//用例名称
@BeanProperty
var name: String = _
//用例状态: -1未执行 0失败 1成功
@BeanProperty
var state: Integer = _
//接口
@BeanProperty
var url: String = _
//方法GET,POST
@BeanProperty
var method: String = _
//post参数json string
@BeanProperty
var paramJsonStr: String = _
//期望输出
@BeanProperty
var expectOutput: String = _
//实际输出
@BeanProperty
var actualOutput: String = _
@BeanProperty
var runTimes: Integer = _
@BeanProperty
var owner: String = _
@BeanProperty
var gmtCreate: Date = _
@BeanProperty
var gmtModify: Date = _
}
实体的数据访问层HttpApiDao
实体的数据访问层HttpApiDao非常简单,只需要