Springboot项目之对H2数据库的增删改查操作

一.H2数据库简介

H2是一个用Java开发的嵌入式数据库,可以直接嵌入到应用项目中
  H2最大的用途在于可以同应用程序打包在一起发布,这样可以非常方便地存储少量结构化数据。
  它的另一个用途是用于单元测试。启动速度快,而且可以关闭持久化功能,每一个用例执行完随即还原到初始状态。
  同时它的占用空间小,jar只有5MB大小
  总结一下,H2数据库就是三个特点:嵌入式,简便,小巧

二.下载与安装

下载链接: H2数据库下载地址.
安装也很简单,一路下一步即可。

三.运行模式

主要是三种模式,常用的是嵌入式(本地)连接模式内存模式

嵌入式连接模式,简单来说,会将数据库的内容保存在本地的文件夹里,项目运行结束关闭之后,数据库数据仍保存着,没有被清除。

内存模式,则是将数据库的数据保存在内存中,项目一旦运行结束关闭,数据库内容将从内存中删除,啥也没有了。

四.Springboot+H2database+JPA实例

1.添加Maven依赖

H2database

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

JPA

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

2.pom配置

#datasource
#h2
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=123456

#jpa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update

这里的话采用的是H2数据库的内存模式

spring.datasource.url=jdbc:h2:mem:testdb

‘mem’就表示内存模式,‘testdb’是数据库名称
然后在浏览器中输入地址‘http://localhost:yourport/h2-console’即可进入h2数据库的登录界面了,如下图所示
在这里插入图片描述

在登录页面中输入你刚才配置的JDBC URL以及用户名和密码,就可以进入H2数据库了。
在这里插入图片描述
然后这就是web管理界面了,跟其他数据库管理系统一样,输入一些SQL语句就可以建表建立数据库了,很简单。

当然,我们自然不会去手动建立这些表,因为还是比较麻烦的,这里我们采用JPA来帮助我们建表。

3.JPA自动建表

spring.jpa.hibernate.ddl-auto=update

自动建表主要靠这个配置,即当数据库中没有这个表时则自动更新及建立—update

首先我们建立一张"product"表,然后表中的话有以下几个字段,先上代码

entity层

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

//表名为“product”
@Entity(name = "product")
public class Product {
	//主键为id且自增
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Id
    int id;
    String subject;
    String coverpath;
    int price;
    String message; 
    
    public String getSubject() {return subject;}
    public void setSubject(String subject){this.subject = subject;}
    public String getCoverpath(){return coverpath;}
    public void setCoverpath(String coverpath){this.coverpath = coverpath;}
    public int getPrice(){return price;}
    public void setPrice(int price){this.price = price;}
    public String getMessage(){return message;}
    public void setMessage(String message){this.message = message;}
    public int getId(){return id;}
    public void setId(int id){this.id = id;}
}

一共五个字段,分别是id,subject,coverpath,price,message。
然后主要使得“id”字段自增长并且设置为主键 ,表名为“product”

dao层

import com.example.h2ttt.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductDao extends JpaRepository<Product, Integer> {
}

主要继承Product类

Service层

import java.util.List;

public interface Productservice {
    List<Product> getALL();
    /**
     * 保存用户对象
     * @param product
     */
    void save(Product product);

    void delete(Integer id);

    void saveAll(Product product);
}

主要定义了4个服务,分别是getALL(),save(),delete(),saveAll(),也就分别对应了查找,保存,删除,保存全部

ServiceImpl层

继承Service层,具体定义几个方法。

import com.example.h2ttt.dao.ProductDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ProductServiceImpl {
    @Autowired
    ProductDao productDao;

    public List<Product> getALL(){
        return productDao.findAll();
    }
    public void save(Product product){productDao.save(product);}
    public void delete(Integer id){productDao.deleteById(id);}
}

向表中插入数据

import com.example.h2ttt.dao.ProductDao;
import com.example.h2ttt.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
public class DataInsert {
    @Autowired
    ProductDao productDao;

    @RequestMapping("/productinsert")
    public String insertproduct(){
        Product product1=new Product();
        product1.setSubject("恩希玛");
        product1.setCoverpath("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=659606990,4153315840&fm=26&gp=0.jpg");
        product1.setPrice(10);
        product1.setMessage("于老师手工制作");

        Product product2=new Product();
        product2.setSubject("打屎棒");
        product2.setCoverpath("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1558787118,782205535&fm=26&gp=0.jpg");
        product2.setPrice(988);
        product2.setMessage("保密交易!不可外传");

        Product product3=new Product();
        product3.setSubject("野鸡");
        product3.setCoverpath("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2701417504,4021536824&fm=26&gp=0.jpg ");
        product3.setPrice(200);
        product3.setMessage("想吃进屋来");

        List<Product> products= Arrays.asList(product1,product2,product3);
        productDao.saveAll(products);
        return "insert products success";
    }
    }

在网页中输入’localhost:port/productinsert’,即可插入这些商品信息,插入成功会返回"insert products success"
然后再打开H2数据库,发现插入数据成功。
在这里插入图片描述

五. 对数据库进行增删改查

1.“查”

在controller层编写以下代码

    @Autowired
    private ProductServiceImpl Productservice;
    @RequestMapping("/index")
    public String index(Model model){
        List<Product> products= Productservice.getALL();
        model.addAttribute("products",products);
        return "index";
    }

然后我们要写一个前端来查看这些数据,代码如下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>管理商品</title>
<style>
    table
    {
        border-collapse:collapse;
    }
    th
    {
        background-color:dodgerblue;
        color:white;
    }
    table,th, td
    {
        border: 1px solid blue;
    }
</style>
</head>
<body>
<div th:align="center"><h2>当前商品展示</h2><br><br></div>

<div th:align="center">
    <table>
        <tr>
            <th>商品id</th>
            <th>商品名称</th>
            <th>商品图片路径</th>
            <th>商品价格</th>
            <th>商品信息</th>
            <th>操作</th>
        </tr>
        <tr th:each="product:${products}">
            <td th:text="${product.id}"></td>
            <td th:text="${product.subject}"></td>
            <td th:text="${product.coverpath}"></td>
            <td th:text="${product.price}"></td>
            <td th:text="${product.message}"></td>
            <td><a href="/delete">删除</a></td>
        </tr>
    </table>
</div>
<div th:align="center"><br><br><a href="/Add">去添加商品</a></div>
</body>
</html>

在这里插入图片描述
index页面如上图所示
在这里插入图片描述

结果如上图所示,将数据库中的商品的所有信息都展示出来。

2.“删”

删除的话这里随便做了一下,主要是点击删除按钮,会跳转到删除商品界面,然后根据商品id删除。

controller层代码

    @RequestMapping("/delete")
    public String delete(Model model){
        model.addAttribute("id","请输入要删除的商品id");
        return "Delete";
    }
    @RequestMapping("/dodel")
    @ResponseBody
    public String del(Integer id){
        Productservice.delete(id);
        return "delete product success";
    }

点击index页面的删除按钮,跳转到“Delete”页面。

Delete.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>删除商品</title>
</head>
<body>
<div th:align="center">
<form action="/dodel" method="post">
    商品id:<input type="text" th:value="${id}" name="id"><br/>
    <button>删除</button>
</form>
</div>
</body>
</html>

这里我们删除5号商品“琥珀鹿”,操作如下
在这里插入图片描述
结果如下,删除成功
在这里插入图片描述

3.“增”

点击index页面中的“去添加商品”,然后就会跳转到Add.html页面
在这里插入图片描述
输入商品信息,保存,即可。

Add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加商品</title>
</head>
<body>
<div th:align="center">
<form action="/save" method="post">
    商品名:<input type="text" th:value="${subject}" name="subject"><br/>
    商品图片路径:<input type="text" th:value="${coverpath}" name="coverpath"><br/>
    商品价格:<input type="text" th:value="${price}" name="price"><br/>
    商品介绍:<input type="text" th:value="${message}" name="message"><br/>
    <button>保存</button>
</form>
</div>
</body>
</html>

controller层代码

    @RequestMapping("/Add")
    public String add(Model model) {
        model.addAttribute("subject", "请输入要添加的商品名称");
        model.addAttribute("coverpath", "请输入要添加的商品图片路径");
        model.addAttribute("price", "请输入要添加的商品价格");
        model.addAttribute("message", "请输入要添加的商品信息");
        return "Add";
    }

    @RequestMapping("/save")
    @ResponseBody
    public String save(Product product) {
        Productservice.save(product);
        return "save product success !";
    }

4.“改”

改动的话,我没有写,但是实现的话只要先删掉商品再重新编辑信息添加即可,偷懒了哈哈哈

总结

H2数据库是一个很方便的内嵌式java数据库,在一个java项目中表现出众,不像mysql,SQL server那样的数据库一样—安装复杂,配置繁琐,管理困难
所以我选择这个数据库来完成一些关联数据库的操作,谁用谁知道~

本博客主要做的是对商品数据的一个增删改查,页面很简单,逻辑也不复杂,一些代码书写的不是特别好,但是是我本人总结的学习经验,总的来说还可以。(有经验的同学直接复制就可以完全实现以上功能的)

想要完整工程代码的可以私我Q626150391
最后的最后,觉得有帮助的记得点个关注点个赞哈~

新增Github源码地址

Github地址: https://github.com/Huge-Hammer/VXprogram-shoppingmall

Spring Boot是一个非常流行的Java框架,可以轻松地创建Web应用程序。Layui是一个流行的前端UI框架,可以帮助我们快速地创建漂亮的Web页面。在这里,我将向你展示如何使用Spring Boot和Layui来实现基本的增删改查功能。 首先,我们需要创建一个Spring Boot项目。你可以使用Spring Initializr来创建一个新项目,也可以使用Eclipse或IntelliJ IDEA等IDE来创建一个新项目。 接下来,我们需要添加一些依赖项。在这个例子中,我们将使用Spring Data JPA来访问数据库。在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> ``` 我们还需要添加Spring Boot和Layui的依赖项。在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>layui</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.1.0</version> </dependency> ``` 接下来,我们需要配置数据库连接。在application.properties文件中添加以下代码: ``` 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 spring.h2.console.enabled=true ``` 在这里,我们使用H2内存数据库来简化示例。在实际应用程序中,你可能需要使用其他数据库,例如MySQL或PostgreSQL。 现在,我们将创建一个实体类来表示我们的数据表。在这个例子中,我们将创建一个简单的数据表,其中包含id,name和age字段。创建一个名为Person的类,并在其中添加以下代码: ```java @Entity @Table(name = "person") public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private int age; // getters and setters } ``` 接下来,我们将创建一个Spring Data JPA存储库来访问数据库。创建一个名为PersonRepository的接口,并在其中添加以下代码: ```java @Repository public interface PersonRepository extends JpaRepository<Person, Long> { } ``` 现在我们已经设置好了数据访问层,我们将创建一个控制器来处理HTTP请求。创建一个名为PersonController的类,并在其中添加以下代码: ```java @Controller public class PersonController { @Autowired private PersonRepository personRepository; @GetMapping("/") public String index(Model model) { List<Person> persons = personRepository.findAll(); model.addAttribute("persons", persons); return "index"; } @GetMapping("/add") public String addForm(Model model) { return "add"; } @PostMapping("/add") public String addSubmit(@ModelAttribute Person person) { personRepository.save(person); return "redirect:/"; } @GetMapping("/edit/{id}") public String editForm(@PathVariable Long id, Model model) { Person person = personRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid person id:" + id)); model.addAttribute("person", person); return "edit"; } @PostMapping("/edit/{id}") public String editSubmit(@PathVariable Long id, @ModelAttribute Person person, BindingResult bindingResult) { if (bindingResult.hasErrors()) { person.setId(id); return "edit"; } personRepository.save(person); return "redirect:/"; } @GetMapping("/delete/{id}") public String delete(@PathVariable Long id) { personRepository.deleteById(id); return "redirect:/"; } } ``` 在这里,我们定义了五个方法来处理HTTP请求: - `index()` - 处理根路径请求,列出所有人员记录。 - `addForm()` - 处理添加人员记录请求,返回一个包含表单的页面。 - `addSubmit()` - 处理添加人员记录请求,将表单提交的数据保存到数据库中。 - `editForm()` - 处理编辑人员记录请求,返回一个包含表单的页面。 - `editSubmit()` - 处理编辑人员记录请求,将表单提交的数据更新到数据库中。 - `delete()` - 处理删除人员记录请求,从数据库中删除指定的记录。 现在我们需要创建HTML模板来呈现数据。创建一个名为index.html的文件,并在其中添加以下代码: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Person List</title> <link rel="stylesheet" type="text/css" href="/webjars/layui/2.5.4/css/layui.css"> <script type="text/javascript" src="/webjars/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript" src="/webjars/layui/2.5.4/layui.js"></script> </head> <body> <div class="layui-container"> <div class="layui-row"> <div class="layui-col-md12"> <h2>Person List</h2> </div> </div> <div class="layui-row"> <div class="layui-col-md12"> <table class="layui-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Actions</th> </tr> </thead> <tbody> <tr th:each="person : ${persons}"> <td th:text="${person.id}"></td> <td th:text="${person.name}"></td> <td th:text="${person.age}"></td> <td> <button class="layui-btn layui-btn-xs" onclick="location.href='/edit/'+${person.id}">Edit</button> <button class="layui-btn layui-btn-danger layui-btn-xs" onclick="location.href='/delete/'+${person.id}">Delete</button> </td> </tr> </tbody> </table> </div> </div> <div class="layui-row"> <div class="layui-col-md12"> <button class="layui-btn" onclick="location.href='/add'">Add Person</button> </div> </div> </div> </body> </html> ``` 这个模板使用Thymeleaf作为模板引擎,并使用Layui来创建漂亮的表格和按钮。它列出了所有人员记录,并提供了添加,编辑和删除记录的链接。 接下来,我们需要创建一个名为add.html的文件,其中包含添加人员记录的表单。添加以下代码: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Add Person</title> <link rel="stylesheet" type="text/css" href="/webjars/layui/2.5.4/css/layui.css"> <script type="text/javascript" src="/webjars/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript" src="/webjars/layui/2.5.4/layui.js"></script> </head> <body> <div class="layui-container"> <div class="layui-row"> <div class="layui-col-md12"> <h2>Add Person</h2> </div> </div> <div class="layui-row"> <div class="layui-col-md12"> <form class="layui-form" method="post" action="/add"> <div class="layui-form-item"> <label class="layui-form-label">Name:</label> <div class="layui-input-block"> <input type="text" name="name" required lay-verify="required" placeholder="Enter name" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">Age:</label> <div class="layui-input-block"> <input type="text" name="age" required lay-verify="required" placeholder="Enter age" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formDemo">Submit</button> <button type="reset" class="layui-btn layui-btn-primary">Reset</button> </div> </div> </form> </div> </div> </div> </body> </html> ``` 这个模板使用Layui创建一个包含name和age字段的表单。当用户提交表单时,它将数据发送到服务器上的/add路由。 接下来,我们需要创建一个名为edit.html的文件,其中包含编辑人员记录的表单。添加以下代码: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Edit Person</title> <link rel="stylesheet" type="text/css" href="/webjars/layui/2.5.4/css/layui.css"> <script type="text/javascript" src="/webjars/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript" src="/webjars/layui/2.5.4/layui.js"></script> </head> <body> <div class="layui-container"> <div class="layui-row"> <div class="layui-col-md12"> <h2>Edit Person</h2> </div> </div> <div class="layui-row"> <div class="layui-col-md12"> <form class="layui-form" method="post" th:action="@{'/edit/'+${person.id}}" th:object="${person}"> <div class="layui-form-item"> <label class="layui-form-label">Name:</label> <div class="layui-input-block"> <input type="text" name="name" required lay-verify="required" th:value="${person.name}" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">Age:</label> <div class="layui-input-block"> <input type="text" name="age" required lay-verify="required" th:value="${person.age}" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formDemo">Submit</button> <button type="reset" class="layui-btn layui-btn-primary">Reset</button> </div> </div> </form> </div> </div> </div> </body> </html> ``` 这个模板使用Layui创建一个包含name和age字段的表单,并将表单数据预填充为当前记录的值。当用户提交表单时,它将数据发送到服务器上的/edit/{id}路由。 最后,我们需要为我们的应用程序创建一个入口点。创建一个名为Application的类,并在其中添加以下代码: ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 现在我们已经设置好了我们的应用程序,运行它并访问http://localhost:8080/,你应该能够看到一个包含所有人员记录的表格,以及添加,编辑和删除记录的链接。 这就是使用Spring Boot和Layui实现网页上增删改查的基本步骤。当然,你可以扩展它以满足你的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值