什麼是JPA?java
一種規範,並不是ORM框架,也就是ORM上統一的規範mysql
用了以後能夠作什麼,爲何要用?git
代碼解釋:redis
實體類spring
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層sql
@Repository
public interface UserDao extends JpaRepository<User, Long> {
}
複製代碼
測試類數據庫
@Autowired
private UserDao userDao;
public void findAllTest() {
System.out.println(userDao.findAll().toString());
}
複製代碼
上面的操做已經完成了一個查詢所有,相信不用在作多餘的解釋了
JPA優勢:主要就是簡單易用,集成方便,能夠不用寫SQL語句api
這裏的環境springboot
這裏使用的是Gradle
下載以後請在IDEA導入項目bash
buildscript {
ext {
springBootVersion = '2.1.0.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java-library'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
}
//Gradle3.4新增了Java-library插件,java-library插件使用了新的依賴配置implementation和api。舊的依賴配置compile被廢棄
dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('mysql:mysql-connector-java')
compileOnly('org.projectlombok:lombok')
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
複製代碼
package com.example.springbootjpademo.entity;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String ename;
protected User() {
}
public User(String name, String ename) {
this.name = name;
this.ename = ename;
}
@Override
public String toString() {
/* JAVA字符串格式化-String.format() %s 字符串類型 %d 整數類型(十進制) */
return String.format("Customer[id=%d, name='%s', ename='%s']", id, name, ename);
}
}
複製代碼
這裏很簡單,直接繼承核心接口JpaRepository
**src/main/java/com/example/springbootjpademo/repository/UserRepository.java **
package com.example.springbootjpademo.repository;
import com.example.springbootjpademo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
複製代碼
修改application.properties 爲 application.yml
src/main/resources/application.yml
spring:
# 數據源配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
jpa:
# 在 SrpingBoot 2.0 版本中,Hibernate 建立數據表的時候,默認的數據庫存儲引擎選擇的是 MyISAM
#(以前好像是 InnoDB,這點比較詭異)。這個參數是在建表的時候,將默認的存儲引擎切換爲 InnoDB 用的。
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
# 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
複製代碼
src/test/java/com/example/springbootjpademo/SpringbootJpaDemoApplicationTests.java
package com.example.springbootjpademo;
import com.example.springbootjpademo.repository.UserRepository;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJpaDemoApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void contextLoads() {
System.out.println(userRepository.findAll().toString());
}
}
複製代碼
若是出現下列等錯誤:
Error:(41, 13) java: 找不到符號
符號: 方法 setName(java.lang.String)
位置: 類型爲com.example.springbootjpademo.entity.User的變量 user
複製代碼
請注意下面的設置是否正確:
src/test/java/com/example/springbootjpademo/SpringbootJpaDemoApplicationTests.java
package com.example.springbootjpademo;
import com.example.springbootjpademo.entity.User;
import com.example.springbootjpademo.repository.UserRepository;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJpaDemoApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void contextLoads() {
System.out.println(userRepository.findAll().toString());
}
@Before
public void add() {
userRepository.save(new User("英雄聯盟", "lol"));
}
//修改操做
@After
public void update() {
// ifPresent 若是存在值,則使用值調用指定的使用者,不然不執行任何操做。
userRepository.findById(1L).ifPresent(user -> {
user.setName("xiugaihou");
userRepository.save(user);
System.out.println(user.toString());
});
}
//刪除
@After
public void del() {
userRepository.findById(2L).ifPresent(user -> userRepository.delete(user));
}
}
複製代碼
最後數據庫的值: