- 使用 Spring Initializr 创建 Spring Boot 应用程序
- 在Spring Boot中配置Cassandra
- 在 Spring Boot 上配置 Tomcat 连接池
- 将Camel消息路由到嵌入WildFly的Artemis上
在本文中,我们将使用在 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 是开源的 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 文件以解决依赖关系。
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 数据库驱动类名是 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 控制台。
1. 我们正在开发基于 servlet 的 Web 应用程序。
2.com.h2database:h2 在类路径中。我们需要遵循 Maven 依赖项。
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
3. 我们正在使用 Spring Boot 开发人员工具或 spring.h2.console.enabled 在 application.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:是否开启远程访问。默认为假。
找到我们演示应用程序的项目结构。
现在找到完整的代码。
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 运行,请查找步骤。
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 数据库中查找数据。
Windows 集成 (NTLM) 身份验证和 Windows 集成 (Kerberos) 之间有什么区别? 如何在IIS6中实现这些 w.r.t. MSDN 最佳答案 Kerberos 和 NTLM
Keycloak是一个用 Java 编写的开源身份验证和身份管理解决方案。它提供了一个nodejs适配器,使用它我能够成功地与express集成。这是有效的路由文件: 'use strict'
这是我关于 Bamboo 的第二个问题 ( My First One )。阅读建议信息后我的理解是,我需要一个构建工具,例如 nAnt 或 MSbuild 来编写一个获取源代码并构建它的脚本(我正在开
可用于将第三方应用程序与 jira 4.3 集成的身份验证方案有哪些?显然,从客户那里获取用户名和密码听起来很荒谬。另外,我知道 oauth 身份验证仅适用于版本 5。请告诉我。谢谢。 附注。我不是在
我有一个使用 DDS 的旧版 C++ 应用程序用于异步通信/消息传递。我需要将此应用程序集成到使用 JMS 进行消息传递的 JavaEE 环境中。除了构建独立的 JMS/DDS 桥接模块之外,我还有其
我正在尝试使用 Whatsapp 发送测试消息,但收到此错误消息: "error":{"code":27,"description":"Recipient not available on chann
我想将 photologue 与我的 Django 应用程序集成,并使用它在车辆库存中显示照片......有点像 Boost Motor Group Inc. 提供的内容。我已经集成了该应用程序,所以
我目前正在尝试弄清楚如何与 fujitsu scansnap 扫描仪集成,但没有从 fujitsu 找到有关 fujitsu scansnap 管理器如何调用您的应用程序并将文件发送到您的应用程序的详
在我的项目中,我使用了 9 个(九个)int-ip:udp-inbound-channel-adapter 和一个 jms:inbound-channel-adapter。 Jms 适配器从服务器接收
在我们当前的原型(prototype)中,大多数标准 HTML 控件都被小程序取代,最重要的是表单提交由小程序触发。 有没有一种方法可以像 一样在服务器端调用关联的操作 ? 本文Applet and
是否可以使用 twilio 号码从 whatsapp 发送/接收短信?有人用whatsapp试过twilio吗?我问过客服,如果可能的话,他说,不确定,但很多人都问过这个问题。 最佳答案 万一其他人来
我们办公室中几乎不存在版本控制,这显然导致了很多麻烦。我们想使用SVN和Notepad++进行设置...任何人都对如何实现此目标有任何想法?我已经开始研究并浏览了这个网站: http://www.sw
曾经有提供这种集成的 spring-modules 项目;但是,该项目现已弃用。现在有没有人继续支持这种集成?谢谢。 最佳答案 工作正在进行中。 http://blog.athico.com/sear
我的理解是,根据 http://wiki.dbpedia.org/Datasets,DBpedia 从 YAGO 获取类层次结构,而不是实体。 .但是,类似 http://dbpedia.org/cl
任何人都可以帮助我如何将 OpenCMS 与 Java Spring Web 应用程序集成。已经用谷歌搜索并浏览了很多网站但没有用。所以,请帮助我。 最佳答案 我认为将 SpringMVC 与 Ope
我正在尝试使用新的 migs getaway (MPGS) 我遵循了下一个 url 中的代码 https://ap-gateway.mastercard.com/api/documentation/i
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 4年前关闭。 Improve thi
我有一个 cmake 项目。我想轻松完成以下操作 搜索光标下任何变量、函数等的声明、定义和引用,这些可能在外部头文件中声明,其路径是在CMakeLists.txt中使用INCLUDE_DIRECTOR
有人能给我指点一下 Objective-C(或 c/c++)库的方向,或者教通过 FTP 上传或下载的教程(Objective-C)吗?最好能展示如何将文件下载到临时目录,然后稍后上传?我不介意针对
集成()给出了非常错误的答案: integrate(function (x) dnorm(x, -5, 0.07), -Inf, Inf, subdivisions = 10000L) # 2.127
我是一名优秀的程序员,十分优秀!