JPA全稱Java Persistence API.JPA通過JDK 5.0注解或XML描述對象-關系表的映射關系,并將運行期的實體對象持久化到數據庫中。
JPA 的目標之一是制定一個可以由很多供應商實現的API,并且開發人員可以編碼來實現該API,而不是使用私有供應商特有的API。
JPA是需要Provider來實現其功能的,hibernate就是JPA Provider中很強的一個,應該說無人能出其右。從功能上來說,JPA就是Hibernate功能的一個子集。
添加相關依賴
添加spring-boot-starter-jdbc依賴:
1
2
3
4
5
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-jpa </ artifactId > </ dependency > |
添加MySQL連接類和連接池類:
1
2
3
4
5
|
< dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < scope >runtime</ scope > </ dependency > |
配置數據源,在application.properties文件配置:
1
2
3
4
5
6
7
8
9
10
11
|
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 username: root password: 123456 jpa: hibernate: ddl-auto: update # 第一次簡表create 后面用update show-sql: true |
注意,如果通過jpa在數據庫中建表,將jpa.hibernate,ddl-auto改為create,建完表之后,要改為update,要不然每次重啟工程會刪除表并新建。
創建實體類
通過@Entity 表明是一個映射的實體類, @Id表明id, @GeneratedValue 字段自動生成
1
2
3
4
5
6
7
8
9
10
|
@Entity public class Account { @Id @GeneratedValue private int id ; private String name ; private double money; ... 省略getter setter } |
Dao層
數據訪問層,通過編寫一個繼承自 JpaRepository 的接口就能完成數據訪問,其中包含了幾本的單表查詢的方法,非常的方便。值得注意的是,這個Account 對象名,而不是具體的表名,另外Interger是主鍵的類型,一般為Integer或者Long
1
2
|
public interface AccountDao extends JpaRepository<Account,Integer> { } |
Web層
在這個栗子中我簡略了service層的書寫,在實際開發中,不可省略。新寫一個controller,寫幾個restful api來測試數據的訪問。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
@RestController @RequestMapping ( "/account" ) public class AccountController { @Autowired AccountDao accountDao; @RequestMapping (value = "/list" , method = RequestMethod.GET) public List<Account> getAccounts() { return accountDao.findAll(); } @RequestMapping (value = "/{id}" , method = RequestMethod.GET) public Account getAccountById( @PathVariable ( "id" ) int id) { return accountDao.findOne(id); } @RequestMapping (value = "/{id}" , method = RequestMethod.PUT) public String updateAccount( @PathVariable ( "id" ) int id, @RequestParam (value = "name" , required = true ) String name, @RequestParam (value = "money" , required = true ) double money) { Account account = new Account(); account.setMoney(money); account.setName(name); account.setId(id); Account account1 = accountDao.saveAndFlush(account); return account1.toString(); } @RequestMapping (value = "" , method = RequestMethod.POST) public String postAccount( @RequestParam (value = "name" ) String name, @RequestParam (value = "money" ) double money) { Account account = new Account(); account.setMoney(money); account.setName(name); Account account1 = accountDao.save(account); return account1.toString(); } } |
通過postman請求測試,代碼已經全部通過測試。
源碼下載:https://github.com/forezp/SpringBootLearning
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/forezp/article/details/70545038