一、創(chuàng)建項(xiàng)目并導(dǎo)入Jap相關(guān)依賴
1.1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-jpa</ artifactId > </ dependency > < dependency > < groupId >com.alibaba</ groupId > < artifactId >druid-spring-boot-starter</ artifactId > < version >1.1.10</ version > </ dependency > < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < scope >runtime</ scope > < version >5.1.27</ version > </ dependency > |
1.2
Application.perteries配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/jpa?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
#將sql語句展示到控制臺
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.database-platform=mysql
#ddl-auto:create----每次運(yùn)行該程序,沒有表格會新建表格,表內(nèi)有數(shù)據(jù)會清空
#ddl-auto:create-drop----每次程序結(jié)束的時(shí)候會清空表
#ddl-auto:update----每次運(yùn)行程序,沒有表格會新建表格,表內(nèi)有數(shù)據(jù)不會清空,只會更新
#ddl-auto:validate----運(yùn)行程序會校驗(yàn)數(shù)據(jù)與數(shù)據(jù)庫的字段類型是否相同,不同會報(bào)錯(cuò)
spring.jpa.hibernate.ddl-auto=update
#采用哪種方言
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
1.1
創(chuàng)建
@Entity
將實(shí)體類Book創(chuàng)建成表,默認(rèn)不指定就是類名,name指定表名
@ID
主鍵
@GeneratedValue
自增長
1.2
創(chuàng)建
1.3
JAP的功能函數(shù)
在這里定義你的查詢規(guī)則就ok了
1.3.1
保存
1.3.2
修改
注:如果數(shù)據(jù)庫中沒有該數(shù)據(jù)則是添加,存在則是修改
1.3.3
刪除
1.3.4
查詢太多就舉例分頁把
三、自定義查詢
同樣還是在BookDao里寫
注:nativeQuery=true代表使用sql語句查詢,默認(rèn)使用JPA ql查詢
四、自定義添加修改
BookDao類
注:@Query @Modifying @Transactional三個(gè)注解一個(gè)不能少
@Modifying
對數(shù)據(jù)庫修改操作
@Transactional
事務(wù)
圖片中的兩種寫法都可以,第一種順序不能顛倒
@Param不是mybatis的那個(gè)這個(gè)是jpa的
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/fernfei/p/12113045.html