您好,登錄后才能下訂單哦!
小編給大家分享一下SpringBoot2.3.0如何配置JPA,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
JPA顧名思義就是Java Persistence API的意思,是JDK 5.0注解或XML描述對象-關系表的映射關系,并將運行期的實體對象持久化到數據庫中。
依賴
<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
spring.jpa.show-sql=true
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
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
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); } }
測試
注意:
查詢所有
插入
以上是SpringBoot2.3.0如何配置JPA的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。