Spring Boot集成H2 数据库

x33g5p2x  于2022-09-24 转载在 Spring  
字(13.1k)|赞(0)|评价(0)|浏览(490)

在本文中,我们将使用在 Spring Boot 应用程序中使用H2 数据库进行CRUD操作。 H2 数据库用作嵌入式、服务器或内存数据库。 Spring Boot 可以在开发阶段自动配置 H2 控制台。 H2 数据库的驱动程序类名称是 org.h2.Driver。在 Spring Boot 应用程序中,所有与数据源、JPA、连接池和 H2 Web 控制台相关的配置都可以在 application.properties 文件中进行。
在这里,我们将创建一个 Spring Boot 应用程序,该应用程序将使用 H2 数据库执行创建、读取、更新和删除操作。在我们的演示应用程序中,我们使用 CrudRepository 来执行 CRUD 操作。

H2 数据库

H2 是开源的 Java SQL 数据库。它非常快并且使用 JDBC API。 H2数据库可以用作嵌入式模式、服务器模式和内存数据库。可以使用浏览器访问控制台。要安装和使用 H2 数据库,请查找步骤。
1. 去官网 link。下载并安装在您的计算机中。
2. 打开 H2 控制台(命令行) 并在浏览器中访问 URL http://localhost:8082。 Spring Boot 还可以在开发阶段为开发人员自动配置 H2 控制台。现在选择服务器模式,在 JDBC URL 中,我们可以根据需要更改“测试”数据库名称。在我们的示例中,我们将数据库名称更改为“mydb”。找到打印屏幕。

要创建表和检查数据,请单击 Connect 按钮。
3. 在我们的演示应用程序中,我们将使用 H2 数据库创建 Spring Boot 应用程序。找到用于创建我们演示中使用的 H2 表的 SQL。

CREATE TABLE IF NOT EXISTS students (
  roll_num bigint(5) NOT NULL AUTO_INCREMENT,
  name varchar(100) NOT NULL,
  age int(3) NOT NULL,
  PRIMARY KEY (roll_num)
);

INSERT INTO students (roll_num, name, age) VALUES
	(1, 'Mahesh', 19),
	(2, 'Krishna', 18);

在 H2 数据库中创建上表来运行我们的演示应用程序。
4. 在服务器模式下,JDBC URL 将为 jdbc:h2:tcp://localhost/~/mydb
5. 如果我们选择嵌入模式,JDBC URL 将为 jdbc:h2:~/mydb
6. 在嵌入式模式下,数据库只能在一个虚拟机(和类加载器)中打开,而在服务器模式下,许多应用程序可以同时连接到同一个数据库,通过连接到这个服务器。
7. 要使用我们的 Spring 应用程序连接到 H2 数据库,我们需要使用驱动程序类名称为 org.h2.Driver 并使用 Maven 依赖项解析它,如下所示。

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
</dependency>

Maven 依赖项

找到 Maven 文件以解决依赖关系。
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.concretepage</groupId>
	<artifactId>spring-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>Spring</name>
	<description>Spring Demo Project</description>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
		<relativePath />
	</parent>
	<properties>
		<context.path>spring-app</context.path>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

连接到 H2 数据库

H2 数据库驱动类名是 org.h2.Driver。在 application.properties 文件中找到 Spring 数据源配置以连接 H2 数据库和服务器模式。

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:tcp://localhost/~/mydb
spring.datasource.username=sa
spring.datasource.password=cp

使用 Spring Boot 配置 H2 Web 控制台

Spring Boot 可以在以下情况下自动配置 H2 Web 控制台。
1. 我们正在开发基于 servlet 的 Web 应用程序。
2.com.h2database:h2 在类路径中。我们需要遵循 Maven 依赖项。

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
</dependency>

3. 我们正在使用 Spring Boot 开发人员工具或 spring.h2.console.enabledapplication.properties 文件中已设置为 true

自动配置 H2 Web 控制台的目的只是在开发阶段而不是在生产阶段。如果我们的应用程序正在使用开发人员工具,并且当我们为生产创建存档文件时,H2 Web 控制台将不会自动可用。
如果我们已将 spring.h2.console.enabled 启用为 true,那么我们必须在为生产创建 JAR/WAR 之前将其设为 false
要在我们的应用程序中使用开发人员工具,我们需要遵循 Maven 依赖项。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
</dependency>

在与 H2 Web 控制台相关的 application.properties 文件中找到要配置的属性。

spring.h2.console.path:默认的 H2 Web 控制台路径,由 Spring Boot 自动配置,是 /h2-console,可以使用此属性进行更改。在我们的示例中,我们设置了可以使用 http://localhost:8080/h2 URL 访问的 spring.h2.console.path=/h2

spring.h2.console.enabled:是否启用控制台。默认为假。

spring.h2.console.settings.trace:是否开启trace输出。默认为假。

spring.h2.console.settings.web-allow-others:是否开启远程访问。默认为假。

Spring Boot + H2 CRUD 示例

找到我们演示应用程序的项目结构。

现在找到完整的代码。
application.properties

#Datasource Configuration
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:tcp://localhost/~/mydb
spring.datasource.username=sa
spring.datasource.password=

#JPA Configuration
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true

#Connection Pool Configuration
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=12
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.max-lifetime=1200000

#H2 Web Console
#spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=true

StudentRepository.java

package com.concretepage.repository;
import org.springframework.data.repository.CrudRepository;
import com.concretepage.entity.Student;
public interface StudentRepository extends CrudRepository<Student, Long>  {
}

IStudentService.java

package com.concretepage.service;
import java.util.List;
import com.concretepage.entity.Student;
public interface IStudentService {
     List<Student> getAllStudents();
     Student getStudentByRollNum(long rollNum);
     boolean addStudent(Student student);
     void updateStudent(Student student);
     void deleteStudent(long rollNum);
}

StudentService.java

package com.concretepage.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.concretepage.entity.Student;
import com.concretepage.repository.StudentRepository;

@Service
public class StudentService implements IStudentService {
	@Autowired
	private StudentRepository studentRepository;

	@Override
	public Student getStudentByRollNum(long rollNum) {
		Student obj = studentRepository.findById(rollNum).get();
		return obj;
	}

	@Override
	public List<Student> getAllStudents() {
		List<Student> list = new ArrayList<>();
		studentRepository.findAll().forEach(e -> list.add(e));
		return list;
	}

	@Override
	public boolean addStudent(Student student) {
		studentRepository.save(student);
		return true;

	}

	@Override
	public void updateStudent(Student student) {
		studentRepository.save(student);
	}

	@Override
	public void deleteStudent(long rollNum) {
		studentRepository.delete(getStudentByRollNum(rollNum));
	}
}

Student.java

package com.concretepage.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="students")
public class Student implements Serializable { 
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="roll_num")
        private long rollNum;  
	@Column(name="name")
        private String name;
	@Column(name="age")	
	private int age;

       //setters and getters
}

StudentController.java

package com.concretepage.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.util.UriComponentsBuilder;
import com.concretepage.entity.Student;
import com.concretepage.service.IStudentService;
@Controller
public class StudentController {
	@Autowired
	private IStudentService studentService;

	@GetMapping("student/{rollNum}")
	public ResponseEntity<Student> getStudentByRollNum(@PathVariable("rollNum") long rollNum) {
		Student student = studentService.getStudentByRollNum(rollNum);
		return new ResponseEntity<Student>(student, HttpStatus.OK);
	}

	@GetMapping("students")
	public ResponseEntity<List<Student>> getAllStudents() {
		List<Student> list = studentService.getAllStudents();
		return new ResponseEntity<List<Student>>(list, HttpStatus.OK);
	}

	@PostMapping("student")
	public ResponseEntity<Void> addStudent(@RequestBody Student student, UriComponentsBuilder builder) {
		studentService.addStudent(student);
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(builder.path("/student/{rollNum}").buildAndExpand(student.getRollNum()).toUri());
		return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
	}

	@PutMapping("student")
	public ResponseEntity<Student> updateStudent(@RequestBody Student student) {
		studentService.updateStudent(student);
		return new ResponseEntity<Student>(student, HttpStatus.OK);
	}

	@DeleteMapping("student/{rollNum}")
	public ResponseEntity<Void> deleteStudent(@PathVariable("rollNum") long rollNum) {
		studentService.deleteStudent(rollNum);
		return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
	}
}

Main.java

package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {  
	public static void main(String[] args) {
		SpringApplication.run(Main.class, args);
        }       
}

运行应用程序

我们可以直接将 Main 类作为 Java 应用程序运行,也可以使用命令提示符通过 mvn spring-boot:run 命令运行。
要将应用程序作为 JAR 运行,请查找步骤。

  1. 使用命令提示符进入项目的根目录并运行mvn clean package 命令。
  2. target 目录中将创建一个 JAR。
  3. 要使用 JAR 运行应用程序,请运行命令。
java -jar target/spring-demo-0.0.1-SNAPSHOT.jar

确保 H2 控制台(命令行) 已在运行。

要打开 Spring Boot 启用的 H2 Web 控制台,我们需要通过将 Main 类作为 Java 应用程序运行或通过 mvn spring-boot:run com 以开发模式启动我们的应用程序使用命令提示符命令。

找到客户端代码来测试应用程序。
RestClientUtil.java

package com.concretepage.client;
import java.net.URI;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.concretepage.entity.Student;
public class RestClientUtil {
	HttpHeaders headers = new HttpHeaders();
	RestTemplate restTemplate = new RestTemplate();

	public void getStudentByRollNumDemo(long rollNum) {
		headers.setContentType(MediaType.APPLICATION_JSON);
		String url = "http://localhost:8080/student/{rollNum}";
		HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
		ResponseEntity<Student> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
				Student.class, rollNum);
		Student student = responseEntity.getBody();

		System.out.println("Roll Num:" + student.getRollNum() + ", Name:" + student.getName() + ", Age:" + student.getAge());
	}

	public void getAllStudentsDemo() {
		headers.setContentType(MediaType.APPLICATION_JSON);
		String url = "http://localhost:8080/students";
		HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
		ResponseEntity<Student[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
				Student[].class);
		Student[] students = responseEntity.getBody();
		for (Student student : students) {
			System.out.println("Roll Num:" + student.getRollNum() + ", Name:" + student.getName() + ", Age:" + student.getAge());
		}
	}
	
	public void addStudentDemo(Student student) {
		headers.setContentType(MediaType.APPLICATION_JSON);
		String url = "http://localhost:8080/student";
		HttpEntity<Student> requestEntity = new HttpEntity<Student>(student, headers);
		URI uri = restTemplate.postForLocation(url, requestEntity);
		System.out.println(uri.getPath());
	}

	public void updateStudentDemo(Student student) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		RestTemplate restTemplate = new RestTemplate();
		String url = "http://localhost:8080/student";
		HttpEntity<Student> requestEntity = new HttpEntity<Student>(student, headers);
		restTemplate.put(url, requestEntity);
	}

	public void deleteStudentDemo(long rollNum) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		RestTemplate restTemplate = new RestTemplate();
		String url = "http://localhost:8080/student/{rollNum}";
		HttpEntity<Student> requestEntity = new HttpEntity<Student>(headers);
		restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Void.class, rollNum);
	}

	public static void main(String args[]) {
		RestClientUtil util = new RestClientUtil();
		Student student = new Student();
		
		student.setName("Shiva");
		student.setAge(19);		
		//util.addStudentDemo(student); //add

		student.setRollNum(2);
		student.setName("Gopal");
		student.setAge(22);		
		//util.updateStudentDemo(student); //update

		//util.deleteStudentDemo(2); //delete
		
		//util.getStudentByRollNumDemo(1); //get by roll number
		
		System.out.println("---- All students ----");
		util.getAllStudentsDemo(); // get all students
	}
}

在 H2 数据库中查找数据。

相关文章

微信公众号

最新文章

更多