Springboot项目之对H2数据库的增删改查操作
一.H2数据库简介H2是一个用Java开发的嵌入式数据库,可以直接嵌入到应用项目中 H2最大的用途在于可以同应用程序打包在一起发布,这样可以非常方便地存储少量结构化数据。 它的另一个用途是用于单元测试。启动速度快,而且可以关闭持久化功能,每一个用例执行完随即还原到初始状态。 同时它的占用空间小,jar只有5MB大小 总结一下,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
更多推荐
所有评论(0)