2021-05-12 14:32:11
SpringBoot2.3.0設定JPA的實現範例
2020-08-13 00:00:34
JPA顧名思義就是Java Persistence API的意思,是JDK 5.0註解或XML描述物件-關係表的對映關係,並將執行期的實體物件持久化到數據庫中。
依賴
- spring-boot-starter-data-jdbc
- spring-boot-starter-data-jpa
- mysql-connector-java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</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> <scope>runtime</scope> </dependency>
application.yml
spring.jpa.hibernate.ddl-auto=update
- 如果數據庫內沒有表或表結構改變時根據Entity建立/更新
spring.jpa.show-sql=true
- 控制檯列印sql
spring.jpa.database
- 指定數據庫型別,可寫可不寫
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/spring_boot?serverTimezone=GMT%2B8 username: root password: root jpa: hibernate: ddl-auto: update show-sql: true database: mysql
POJO
- @Data是Lombok
- @Entity告訴JPA這是一個實體類(和數據表對映的類)
- @Table(name = 「jpa_user」) 給表起名,不寫預設爲類名小寫(user)
- @Id設定主鍵
- @GeneratedValue(strategy = GenerationType.IDENTITY) 使用自增
- @Column(name = 「jpa_username」,length = 40) 給列起名,不寫預設爲屬性名(username)
import lombok.Data; import javax.persistence.*; @Entity @Table(name = "jpa_user") @Data public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "jpa_username",length = 40) private String username; @Column(name = "jpa_password") private String password; }
Repository
JpaRepository的繼承關係
所以繼承JpaRepository
- JpaRepository<T, ID>
- 第一個泛型就是要操作的Entity
- 第二個泛型就是Entity的Id主鍵型別
- JpaRepository<User, Integer>
package com.live.repository; import com.live.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,Integer> { }
Controller(測試)
@Autowired @Autowired UserRepository userRepository;
package com.live.controller; import com.live.model.User; import com.live.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Optional; @RestController public class UserJPAController { @Autowired UserRepository userRepository; @GetMapping("/findAll") public List<User> findAll() { return userRepository.findAll(); } @GetMapping("/findOne/{id}") public Optional<User> findOne(@PathVariable(value = "id") Integer id) { return userRepository.findById(id); } @GetMapping("/insert") public User insertOne(User user) { return userRepository.save(user); } }
測試
注意:
- 對欄位操作時,使用的是實體類的屬性名(username,password)
- 而不是在@Column(name=「jpa_username」)設定的jpa_username
查詢所有
插入
到此這篇關於SpringBoot2.3.0設定JPA的實現範例的文章就介紹到這了,更多相關SpringBoot2.3.0設定JPA內容請搜尋it145.com以前的文章或繼續瀏覽下面 下麪的相關文章希望大家以後多多支援it145.com!
相關文章