- 项目整体结构目录:
- pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
</dependencies>
- application.properties
#the log level
logging.level.org.springframework=debug
#configure the datasource, type equal default
spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.schema=classpath:db/schema.sql
spring.datasource.data=classpath:db/data.sql
#configure the h2 web console
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.h2.console.settings.web-allow-others=true
#configure the jpa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.platform=h2
#config the thymeleaf template
spring.thymeleaf.enabled=true
spring.thymeleaf.mode=HTML5
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
H2内存数据库依靠配置中的classpath:db/schema.sql来创建表
classpath:db/data.sql 向数据库中插入数据,红色字体不要管,不影响代码的运行。
- Student类
package com.yueqin.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;
import javax.persistence.*;
import java.util.Date;
@Component
@Entity
@Table(name="studnet")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column
private String name;
@Column
private int age;
@Column
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") //转入
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") //json转出
private Date birthday;
@Column
private String address;
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
", address='" + address + '\'' +
'}';
}
}
- StudentService类
package com.yueqin.Service;
import com.yueqin.Repository.StudentRepository;
import com.yueqin.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public Student insertOne(Student student){
Student stu = studentRepository.save(student);
return stu;
}
public int insertAll (List<Student> students){
List<Student> studentList = studentRepository.saveAll(students);
return studentList.size();
}
public Student findStudentById(int id){
Optional<Student> student = studentRepository.findById(id);
if(student.isPresent()){
return student.get();
}else{
return null;
}
}
public Student findStudentByName(String name){
Student stu = studentRepository.findStudentByNameIsLike(name);
return stu;
}
public void deleteStudentById(int id){
studentRepository.deleteById(id);
}
public void deleteAll(){
studentRepository.deleteAll();
}
public Student updateStudent(Student student){
Student update = studentRepository.save(student);
return update;
}
}
- HTML
注意 在用到thymeleaf时候,html声明<html lang="en" xmlns:th="http://www.thymeleaf.org">
一定要写上不然起不到作用。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>提交页</title>
<style>
*{
margin: 10px 10px;
}
input{
border-radius: 1px;
}
span{
width:88px;
}
</style>
</head>
<body>
<form method="post" action="/save">
<span>name : </span><input type="text" name="name" size="30"/><br/>
<span>age : </span><input type="text" name="age" size="30" /><br/>
<span>birthday : </span><input type="text" name="birthday" placeholder="yyyy-MM-dd HH:mm:ss" size="30"/><br/>
<span>address : </span><input type="text" name="address" size="30"/><br/>
<div class="button">
<input type="reset" value="reset"/>
<input type="submit" value="submit"/>
</div>
</form>
</body>
</html>
- 插入一条数据
- 得到的JSON响应
@RestController
public class StudentController {
@Autowired
private StudentService service;
@PostMapping("/save")
public Student saveStudent(Student student) throws JsonProcessingException {
Student stu = service.insertOne(student);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(stu));
return stu;
}
}
可以看到插入成功并返回json数据了
- 登录h2的控制台去查看数据库的数据 http://localhost:8080/h2-console
查看application.properies在以下的表格中填入相关的参数:
spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console #路径
10. 输入SQL语句查询数据
注意: 可以看到有两个Student表,其中第一个是保存data.sql脚本执行结果用于插入数据的Student表,第二个是用于保存我们表单提交的Student表。
可以看到数据已经成功插入到h2数据库了。
H2数据库是一个内存数据库,那么它不具备数据持久化能力,它的生命周期是等同于spring的生命周期,当你启动项目的时候,h2同时被激活,当你关闭项目的时候h2同时被销毁,数据也会被清空,所以h2可以做一些缓存的作用,存储一些临时的数据。另外h2数据库可以很好的融入spring工程,快速运用,而不用再去构建mysql,或者oracle。在一些web容器的内部,比如jboss,tomcat,weblogic里面,可以运用h2来做一个数据源的测试数据库。