javascript
企业级 SpringBoot 教程 (四)SpringBoot 整合JPA
JPA全稱Java Persistence API.JPA通過JDK 5.0注解或XML描述對象-關系表的映射關系,并將運行期的實體對象持久化到數據庫中。
JPA 的目標之一是制定一個可以由很多供應商實現的API,并且開發人員可以編碼來實現該API,而不是使用私有供應商特有的API。
JPA是需要Provider來實現其功能的,Hibernate就是JPA Provider中很強的一個,應該說無人能出其右。從功能上來說,JPA就是Hibernate功能的一個子集。
添加相關依賴
添加spring-boot-starter-jdbc依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>復制代碼添加mysql連接類和連接池類:
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>復制代碼配置數據源,在application.properties文件配置:
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8username: rootpassword: 123456jpa:hibernate:ddl-auto: update # 第一次簡表create 后面用updateshow-sql: true復制代碼注意,如果通過jpa在數據庫中建表,將jpa.hibernate,ddl-auto改為create,建完表之后,要改為update,要不然每次重啟工程會刪除表并新建。
創建實體類
通過@Entity 表明是一個映射的實體類, @Id表明id, @GeneratedValue 字段自動生成
@Entity public class Account {@Id@GeneratedValueprivate int id ;private String name ;private double money;... 省略getter setter }復制代碼Dao層
數據訪問層,通過編寫一個繼承自 JpaRepository 的接口就能完成數據訪問,其中包含了幾本的單表查詢的方法,非常的方便。值得注意的是,這個Account 對象名,而不是具體的表名,另外Interger是主鍵的類型,一般為Integer或者Long
public interface AccountDao extends JpaRepository<Account,Integer> { }復制代碼完整項目的源碼來源 技術支持1791743380
轉載于:https://juejin.im/post/5c739756f265da2dd94cb19c
總結
以上是生活随笔為你收集整理的企业级 SpringBoot 教程 (四)SpringBoot 整合JPA的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: es6 find 数组内查询用法
- 下一篇: 随机森林算法4种实现方法对比测试:Dol