English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Cos'è un database in memoria
I database in memoria dipendono dalla memoria del sistema piuttosto che dallo spazio di archiviazione dei dati su disco. Poiché l'accesso alla memoria è più veloce dell'accesso al disco. Utilizziamo i database in memoria quando non abbiamo bisogno di persistere i dati. I database in memoria sono database embedded. Di default, i database in memoria sono volatile, i dati memorizzati vengono persi quando riavviamo l'applicazione. I database in memoria più utilizzati sono H2, HSQLDB (HyperSQL database)e , Apache Derby.
Persistenza e database in memoria database persistenti memorizzano i dati permanentemente nella memoria fisica. Anche se il server del database si riavvia, i dati saranno disponibili. Alcuni database persistenti popolari sonoOracle, MySQL, Postgres,
per nei database in memoriamemoria del sistema La chiusura del programma perde i dati. È utile perin. POC (prova di concetto) molto utile, ma non utile per le applicazioni in produzione. I database in memoria più utilizzati sono H2.
H2 è 嵌入式, open sourcee memoriaÈ un sistema di gestione del database relazionale scritto in Java. Questo è un database client/serverapplicazione. Solitamente viene utilizzato per Test di unità. memorizza i dati in memoria invece di memorizzarli permanentemente sul disco.
Vantaggi
Zero configurazione Facile da usare. Leggero e veloce. Fornisce una configurazione semplice che permette di passare da un database reale a un database in memoria. Supporta gli standard SQL e JDBC API. fornisce una console web che può essere mantenuta nel database.
Se si desidera utilizzare il database H2 nell'applicazione, è necessario aggiungere le seguenti dipendenze nel file pom.xml:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
Dopo aver aggiunto la dipendenza, dobbiamo configurare il database H2 l'URL del data source, il nome della classe del driver, il nome utentee 密码. Spring Boot fornisce un metodo semplice per configurare application.properties queste proprietà nel file.
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
in spring.datasource.url nelle proprietà mem è il nome del database in memoria, mentre testdb è il nome del database in memoria. Di default, l'architettura fornita da H2. Possiamo anche definire la nostra architettura e il database. Il nome utente di default è sa ,la password vuota significa VuotoPassword. Se si desidera modificare il nome utente e la password, è possibile sovrascrivere questi valori.
Se si desidera conservare i dati nel database H2, dovremmo salvare i dati in un file. Per fare questo, dobbiamo modificare l'attributo URL del sorgente di dati.
#Salvare i dati spring.datasource.url=jdbc:h2:file:/data/sampledata spring.datasource.url=jdbc:h2:C:/data/sampledata
Nella seguente proprietà, sampledata è un nome di file.
Possiamo definire attraverso resource Creare in SQL Creare un file per creare lo schema /main/resource).
schema.sql
DROP TABLE IF EXISTS CITY; CREATE TABLE CITY ( City_code int AUTO_INCREMENT PRIMARY KEY, city_name VARCHAR(50) NOT null, city_pincode INT(8) NOT null, );
Possiamo definire attraverso resource Creare un file in SQL file per riempire i dati nella tabella.
data.sql
INSERT INTO CITY VALUES ('Delhi', 110001); INSERT INTO CITY VALUES ('Kanpur', 208001); INSERT INTO CITY VALUES ('Lucknow', 226001);
Spring Boot raccoglie automaticamente data.sql E eseguirlo per il database H2.
Per default, la vista console del database H2 è disabilitata. Prima di accedere al database H2, dobbiamo abilitarla utilizzando le seguenti proprietà.
#启用H2 consolespring.h2.console.enabled=true
Una volta abilitato il console H2, ora possiamo accedere al console H2 nel browser chiamando l'URL http://localhost:8080/h2-console. La seguente immagine mostra la vista console del database H2.
Nella schermata rapida sopra, abbiamo definito un nome w3codebox .
Configuriamo un Spring Boot.
Passo 1: Apri Spring Initializr http://start.spring.io .
步骤2: 选择Spring Boot版本 2.3.0.M1。
步骤2: 提供 Group名称。我们提供了 com.w3codebox。
步骤3: 提供 Artifact ID。我们提供了 spring-boot-h2-database-example。
步骤5: 添加依赖项 Spring Web,Spring Data JPA ,e H2数据库。
步骤6: clicca Generate (生成)按钮。当我们单击"生成"按钮时,它会将项目包装在 Jar 文件中,并将其下载到本地系统。
步骤7: 提取 Jar文件并将其粘贴到STS工作区中。
第8步: 导入项目文件夹到STS。
文件->导入->现有Maven项目->浏览->选择文件夹spring-boot-h2-database-example->完成
导入需要一些时间。
步骤9: src/main/java文件夹中的名称 com.w3codebox.model 。
步骤10: 包 com.w3codebox.model中的类。 我们创建了名为 Student的类。 在"图书"类中,我们执行了以下操作:
定义四个变量 id, age, namee 生成Getter和Setters。
右键单击文件-> Source-> Generate Getters and Setters。 usare annotazioni @Entity,将类标记为 Entity 。 usare annotazioni @Table将该类标记为 Table 名称。 通过使用注解 @Column 将每个变量定义为 Column 。
Student.java
package com.w3codebox.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; //将类标记为实体 @Entity //定义类名为表名 @Table public class Student { //将id标记为主键 @Id //将id定义为列名 @Column private int id; //将name定义为列名 @Column private String name; //设定年龄age为列名 @Column private int age; // Definire email come nome della colonna @Column private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
passo 11: 在文件夹 src/main/java中创建一个名称为 com.w3codebox.controller 的包。
StudentController.java
package com.w3codebox.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.w3codebox.model.Student; import com.w3codebox.service.StudentService; //creating RestController @RestController public class StudentController { //自动装配 StudentService 类 @Autowired StudentService studentService; //创建从数据库检索所有学生详细信息的get映射 @GetMapping("/student") private List<Student> getAllStudent() { return studentService.getAllStudent(); } //创建检索特定学生详细信息的get映射 @GetMapping("/student/{id}") private Student getStudent(@PathVariable("id") int id) { return studentService.getStudentById(id); } //创建删除映射,删除特定的学生 @DeleteMapping("/student/{id}") private void deleteStudent(@PathVariable("id") int id) { studentService.delete(id); } //创建在数据库中发布学生详细信息的post映射 @PostMapping("/student") private int saveStudent(@RequestBody Student student) { studentService.saveOrUpdate(student); return student.getId(); } }
步骤13: 在文件夹 src/main/java中创建名称为 com.w3codebox.service 的包。
步骤14: 创建一个 Service 类。我们在包 com.w3codebox.service。
StudentService.java 中创建了名为 StudentService 的服务类。
package com.w3codebox.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.w3codebox.model.Student; import com.w3codebox.repository.StudentRepository; @Service public class StudentService { @Autowired StudentRepository studentRepository; //获取所有学生记录 public List<Student> getAllStudent() { List<Student> students = new ArrayList<Student>(); studentRepository.findAll().forEach(student -> students.add(student)); return students; } //获取特定记录 public Student getStudentById(int id) { return studentRepository.findById(id).get(); } public void saveOrUpdate(Student student) { studentRepository.save(student); } //删除特定记录 public void delete(int id) { studentRepository.deleteById(id); } }
步骤15: 在文件夹 src/main/java中创建一个名称为 com.w3codebox.repository 的包。
步骤16: 创建一个 存储库界面。我们在包 com.w3codebox.repository中创建了名称为 StudentRepository 的存储库接口。 它扩展了 Crud Repository 界面。
StudentRepository.java
package com.w3codebox.repository; import org.springframework.data.repository.CrudRepository; import com.w3codebox.model.Student; public interface StudentRepository extends CrudRepository<Student, Integer> { }
现在,我们将在 application.properties 文件中配置数据源 URL,驱动程序类名称,用户名e 密码。
步骤17: Apri application.properties 文件并配置以下属性。
application.properties
spring.datasource.url=jdbc:h2:mem:w3codebox spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect #启用H2 consolespring.h2.console.enabled=true
之后创建所有类和包后,项目目录如下所示。
现在,我们将运行该应用程序。
步骤18: Apri SpringBootH2DatabaseExampleApplication.java 文件并将其作为Java应用程序运行。
SpringBootH2DatabaseExampleApplication.java
package com.w3codebox; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootH2DatabaseExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootH2DatabaseExampleApplication.class, args); } }
Nella prossima fase, utilizzeremo il resto dei client PostmanInvia POST e GET Richiesta 。 Se Postman non è installato nel tuo sistema, esegui i seguenti passaggi:
aggiungi l'estensione Google Chrome da https://www.getpostman.com/downloads/ o nel browser https://bit.ly/1HCOCwF. Avvia Postman eRegistratiCrea un nome utente. Abbiamo creato un nome chiamato w3codebox degli utenti, e hai cliccato InviaPassaggio 19: Apri PostmanE esegui le seguenti operazioni:
Scegli POST Chiama l'URL http: //localhost: 8080/student。 ScegliCorpo Scegli il tipo di contenuto JSON(application/json) Inserisci i dati. Abbiamo inserito i seguenti dati nel testo:{ "id": "001", "age": "23", "name": "Amit", "email": "[email protected]" }
Dopo l'esecuzione del comando con successo, viene visualizzato Stato: 200 OK Questo significa che la registrazione è stata inserita con successo nel database.
Allo stesso modo, abbiamo inserito i seguenti dati.
{"id": "002","age": "24","name": "Vadik","email": "[email protected]"} } { "id": "003", "age": "21", "name": "Prateek", "email": "[email protected]" } { "id": "004", "age": "25", "name": "Harsh", "email": "[email protected]" } { "id": "005" "age": "24", "name": "Swarit", "email": "[email protected]" }
Vediamo il console H2 per visualizzare i dati.
Passaggio 20: Apri il browser e chiama l'URL http://localhost:8080/h2-console. Clicca Connect pulsante come segue.
clicca connessionepulsante, vedremo nel database Studenttabella come segue.
Passaggio 21: clicca Studenttabella e poi clicca Eseguipulsante. La tabella mostra i dati che abbiamo inserito nel corpo.
Passaggio 22: Apri Postman e invia GET richiesta. Restituisce i dati che abbiamo inserito nel database.
Inviiamo una richiesta utilizzando l'URL http://localhost: 8080/student/{id}. GET richiesta. Abbiamo chiamato l'URL http://localhost:8080/student/3. Ha restituito i dettagli dello studente con ID 3.
Allo stesso modo, possiamo inviare anche Delete richiesta. Supponiamo di voler eliminare la registrazione dello studente con ID 2.
Per eliminare la registrazione dello studente, invia una richiesta con l'URL http://localhost:8080/student/. DELETE richiesta. Vediamo che l'ID è 2 e lo studente è stato eliminato dal database.