一種規範,並不是ORM框架,也就是ORM上統一的規範java
用了以後能夠作什麼,爲何要用?以下代碼解釋
實體類git
package com.example.springredis.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.io.Serializable; @Entity @Data public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String account; private String pwd; }
dao層github
@Repository public interface UserDao extends JpaRepository<User, Long> { }
測試類web
@Autowired private UserDao userDao; public void findAllTest() { System.out.println(userDao.findAll().toString()); }
上面的操做已經完成了一個查詢所有,相信不用在作多餘的解釋了redis
JPA優勢:主要就是簡單易用,集成方便,能夠不用寫SQL語句spring
這裏使用的是Maven,下載以後請在IDEA導入項目sql
國外依賴下載慢,更換阿里源
<?xml version="1.0" encoding="UTF-8"?> <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>springboot-jpa</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-jpa</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <!--阿里雲主倉庫,代理了maven central和jcenter倉庫--> <repository> <id>aliyun</id> <name>aliyun</name> <url>https://maven.aliyun.com/repository/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <!--阿里雲代理Spring 官方倉庫--> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://maven.aliyun.com/repository/spring</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project>
package com.example.demo.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Data @NoArgsConstructor @AllArgsConstructor @Entity(name = "sys_user") public class SysUser { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String email; private String username; private String password; public SysUser(String email, String username, String password) { this.email = email; this.username = username; this.password = password; } }
**SysUser**
類, @NoArgsConstructor
默認構造函數僅爲JPA而存在。@Entity
註解,表示這個是一個 JPA 的實體,若是在類上沒有加 @Table
註解,代表該實體將映射到名爲 sys_user
的表,若是要加上,能夠在其 name 屬性裏寫入表名,如: @Table(name = "t_user")
id
屬性使用 @Id
註釋,以便JPA將其識別爲對象的ID.這裏很簡單,直接繼承核心接口 JpaRepository
package com.example.demo.repository; import com.example.demo.model.SysUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<SysUser, Long> { }
修改application.properties 爲 application.yml數據庫
src/main/resources/application.ymlapache
spring: datasource: driverClassName: org.h2.Driver password: root url: jdbc:h2:mem:demodb:file:data/demo username: root jpa: open-in-view: true database-platform: org.hibernate.dialect.H2Dialect # spring.jpa.show-sql=true 配置在日誌中打印出執行的 SQL 語句信息。 show-sql: true # 配置指明在程序啓動的時候要刪除而且建立實體類對應的表。 # create 這個參數很危險,由於他會把對應的表刪除掉而後重建。因此千萬不要在生成環境中使用。只有在測試環境中,一開始初始化數據庫結構的時候才能使用一次。 # ddl-auto:create----每次運行該程序,沒有表格會新建表格,表內有數據會清空 # ddl-auto:create-drop----每次程序結束的時候會清空表 # ddl-auto:update----每次運行程序,沒有表格會新建表格,表內有數據不會清空,只會更新(推薦) # ddl-auto:validate----運行程序會校驗數據與數據庫的字段類型是否相同,不一樣會報錯 hibernate.ddl-auto: update
在resources 文件夾下新建 data.sql
data.sql json
DROP TABLE IF EXISTS sys_user; CREATE TABLE sys_user ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(250) DEFAULT NULL, username VARCHAR(250) NOT NULL, password VARCHAR(250) NOT NULL );
package com.example.demo; import com.example.demo.model.SysUser; import com.example.demo.repository.UserRepository; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootJpaApplicationTests { @Autowired private UserRepository userRepository; @Before public void add() { userRepository.save(new SysUser("123@qq.com", "root", "root")); } @Test public void contextLoads() { System.out.println(userRepository.findAll().toString()); } //修改操做 @After public void update() { // ifPresent 若是存在值,則使用值調用指定的使用者,不然不執行任何操做。 userRepository.findById(1L).ifPresent(user -> { user.setUsername("馬華雲騰"); userRepository.save(user); System.out.println(user.toString()); }); } //刪除 @After public void del() { userRepository.findById(2L).ifPresent(user -> userRepository.delete(user)); } }
若是出現下列等錯誤:
Error:(41, 13) java: 找不到符號 符號: 方法 setName(java.lang.String) 位置: 類型爲com.example.springbootjpademo.entity.User的變量 user
請注意下面的設置是否正確:
### 新增1 POST http://localhost:8080/user/add Content-Type: application/json { "email": "eyck@aws.com", "username": "root", "password": "root" } ### 新增2 POST http://localhost:8080/user/add Content-Type: application/json { "email": "ekko@aws.com", "username": "ekko", "password": "ekko" } ### 修改 PUT http://localhost:8080/user/update Content-Type: application/json { "id": 1, "email": "eyck@aws.com", "username": "root", "password": "root" } ### 獲取全部 GET http://localhost:8080/user/all Accept: */* Cache-Control: no-cache ### 刪除 PUT http://localhost:8080/user/del/2 ### 獲取全部 GET http://localhost:8080/user/all Accept: */* Cache-Control: no-cache
左上角 Run all ...
測試結果....
https://github.com/Gleans/spring-boot/tree/master/springboot-jpa