spring boot 数据访问与数据库集成
18.1 学习目标与重点提示
学习目标:掌握spring boot数据访问与数据库集成的核心概念与使用方法,包括spring boot数据访问的基本方法、spring boot与mysql的集成、spring boot与h2的集成、spring boot与mybatis的集成、spring boot与jpa的集成、spring boot的事务管理、spring boot的实际应用场景,学会在实际开发中处理数据库访问问题。
重点:spring boot数据访问的基本方法、spring boot与mysql的集成、spring boot与h2的集成、spring boot与mybatis的集成、spring boot与jpa的集成、spring boot的事务管理、spring boot的实际应用场景。
18.2 spring boot数据访问概述
spring boot数据访问是指使用spring boot进行数据库操作的方法。
18.2.1 数据访问的定义
定义:数据访问是指使用spring boot进行数据库操作的方法。
作用:
- 实现数据库的增删改查。
- 实现事务管理。
- 实现数据的持久化。
✅ 结论:数据访问是指使用spring boot进行数据库操作的方法,作用是实现数据库的增删改查、事务管理、数据的持久化。
18.2.2 数据访问的常用组件
定义:数据访问的常用组件是指spring boot提供的数据访问组件。
组件:
- jdbctemplate:用于jdbc操作。
- jpa:用于jpa操作。
- mybatis:用于mybatis操作。
- hibernate:用于hibernate操作。
✅ 结论:数据访问的常用组件包括jdbctemplate、jpa、mybatis、hibernate。
18.3 spring boot与mysql的集成
spring boot与mysql的集成是最常用的数据访问方法之一。
18.3.1 集成mysql的步骤
定义:集成mysql的步骤是指使用spring boot与mysql集成的方法。
步骤:
- 在pom.xml文件中添加mysql依赖。
- 在application.properties或application.yml文件中配置mysql连接信息。
- 创建实体类。
- 创建repository接口。
- 创建控制器类。
- 测试应用。
示例:
pom.xml文件中的mysql依赖:
<dependencies>
<!-- web依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<!-- data jpa依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-jpa</artifactid>
</dependency>
<!-- mysql依赖 -->
<dependency>
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
<scope>runtime</scope>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-test</artifactid>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的mysql连接信息:
# 服务器端口 server.port=8080 # 数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf-8&usessl=false&servertimezone=utc spring.datasource.driver-class-name=com.mysql.cj.jdbc.driver spring.datasource.username=root spring.datasource.password=123456 # jpa配置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
实体类:
import javax.persistence.*;
@entity
@table(name = "product")
public class product {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string productid;
private string productname;
private double price;
private int sales;
public product() {
}
public product(string productid, string productname, double price, int sales) {
this.productid = productid;
this.productname = productname;
this.price = price;
this.sales = sales;
}
// getter和setter方法
public long getid() {
return id;
}
public void setid(long id) {
this.id = id;
}
public string getproductid() {
return productid;
}
public void setproductid(string productid) {
this.productid = productid;
}
public string getproductname() {
return productname;
}
public void setproductname(string productname) {
this.productname = productname;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
public int getsales() {
return sales;
}
public void setsales(int sales) {
this.sales = sales;
}
@override
public string tostring() {
return "product{" +
"id=" + id +
", productid='" + productid + '\'' +
", productname='" + productname + '\'' +
", price=" + price +
", sales=" + sales +
'}';
}
}repository接口:
import org.springframework.data.jpa.repository.jparepository;
import org.springframework.stereotype.repository;
import java.util.list;
@repository
public interface productrepository extends jparepository<product, long> {
list<product> findbysalesgreaterthan(int sales);
}控制器类:
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
import java.util.list;
@restcontroller
@requestmapping("/api/products")
public class productcontroller {
@autowired
private productrepository productrepository;
@getmapping("/")
public list<product> getallproducts() {
return productrepository.findall();
}
@postmapping("/")
public product addproduct(@requestbody product product) {
return productrepository.save(product);
}
@getmapping("/top-selling")
public list<product> gettopsellingproducts(@requestparam int topn) {
list<product> products = productrepository.findbysalesgreaterthan(0);
products.sort((p1, p2) -> p2.getsales() - p1.getsales());
if (products.size() > topn) {
return products.sublist(0, topn);
}
return products;
}
}测试类:
import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import java.util.list;
import static org.junit.jupiter.api.assertions.assertequals;
@springboottest
class productapplicationtests {
@autowired
private productcontroller productcontroller;
@test
void contextloads() {
}
@test
void testgetallproducts() {
list<product> products = productcontroller.getallproducts();
assertequals(5, products.size());
}
@test
void testaddproduct() {
product product = new product("p006", "平板", 2000.0, 70);
product addedproduct = productcontroller.addproduct(product);
assertequals("p006", addedproduct.getproductid());
}
@test
void testgettopsellingproducts() {
list<product> topsellingproducts = productcontroller.gettopsellingproducts(3);
assertequals(3, topsellingproducts.size());
assertequals("p004", topsellingproducts.get(0).getproductid());
assertequals("p005", topsellingproducts.get(1).getproductid());
assertequals("p001", topsellingproducts.get(2).getproductid());
}
}✅ 结论:集成mysql的步骤包括添加mysql依赖、配置mysql连接信息、创建实体类、创建repository接口、创建控制器类、测试应用。
18.4 spring boot与h2的集成
spring boot与h2的集成是用于开发和测试的常用方法之一。
18.4.1 集成h2的步骤
定义:集成h2的步骤是指使用spring boot与h2集成的方法。
步骤:
- 在pom.xml文件中添加h2依赖。
- 在application.properties或application.yml文件中配置h2连接信息。
- 创建实体类。
- 创建repository接口。
- 创建控制器类。
- 测试应用。
示例:
pom.xml文件中的h2依赖:
<dependencies>
<!-- web依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<!-- data jpa依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-jpa</artifactid>
</dependency>
<!-- h2数据库依赖 -->
<dependency>
<groupid>com.h2database</groupid>
<artifactid>h2</artifactid>
<scope>runtime</scope>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-test</artifactid>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的h2连接信息:
# 服务器端口 server.port=8080 # 数据库连接信息 spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.driver spring.datasource.username=sa spring.datasource.password=password # jpa配置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true # h2数据库控制台 spring.h2.console.enabled=true spring.h2.console.path=/h2-console
实体类、repository接口、控制器类、测试类与集成mysql的示例相同。
✅ 结论:集成h2的步骤包括添加h2依赖、配置h2连接信息、创建实体类、创建repository接口、创建控制器类、测试应用。
18.5 spring boot与mybatis的集成
spring boot与mybatis的集成是常用的数据访问方法之一。
18.5.1 集成mybatis的步骤
定义:集成mybatis的步骤是指使用spring boot与mybatis集成的方法。
步骤:
- 在pom.xml文件中添加mybatis依赖。
- 在application.properties或application.yml文件中配置mybatis连接信息。
- 创建实体类。
- 创建mapper接口。
- 创建mapper xml文件。
- 创建控制器类。
- 测试应用。
示例:
pom.xml文件中的mybatis依赖:
<dependencies>
<!-- web依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupid>org.mybatis.spring.boot</groupid>
<artifactid>mybatis-spring-boot-starter</artifactid>
<version>2.3.0</version>
</dependency>
<!-- mysql依赖 -->
<dependency>
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
<scope>runtime</scope>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-test</artifactid>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的mybatis连接信息:
# 服务器端口 server.port=8080 # 数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf-8&usessl=false&servertimezone=utc spring.datasource.driver-class-name=com.mysql.cj.jdbc.driver spring.datasource.username=root spring.datasource.password=123456 # mybatis配置 mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.demo.entity
实体类:
public class product {
private long id;
private string productid;
private string productname;
private double price;
private int sales;
public product() {
}
public product(string productid, string productname, double price, int sales) {
this.productid = productid;
this.productname = productname;
this.price = price;
this.sales = sales;
}
// getter和setter方法
public long getid() {
return id;
}
public void setid(long id) {
this.id = id;
}
public string getproductid() {
return productid;
}
public void setproductid(string productid) {
this.productid = productid;
}
public string getproductname() {
return productname;
}
public void setproductname(string productname) {
this.productname = productname;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
public int getsales() {
return sales;
}
public void setsales(int sales) {
this.sales = sales;
}
@override
public string tostring() {
return "product{" +
"id=" + id +
", productid='" + productid + '\'' +
", productname='" + productname + '\'' +
", price=" + price +
", sales=" + sales +
'}';
}
}mapper接口:
import org.apache.ibatis.annotations.mapper;
import java.util.list;
@mapper
public interface productmapper {
list<product> findall();
int insert(product product);
list<product> findbysalesgreaterthan(int sales);
}mapper xml文件(src/main/resources/mapper/productmapper.xml):
<?xml version="1.0" encoding="utf-8" ?>
<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.productmapper">
<resultmap id="productresultmap" type="com.example.demo.entity.product">
<id property="id" column="id"/>
<result property="productid" column="product_id"/>
<result property="productname" column="product_name"/>
<result property="price" column="price"/>
<result property="sales" column="sales"/>
</resultmap>
<select id="findall" resultmap="productresultmap">
select * from product
</select>
<insert id="insert" parametertype="com.example.demo.entity.product">
insert into product (product_id, product_name, price, sales) values (#{productid}, #{productname}, #{price}, #{sales})
</insert>
<select id="findbysalesgreaterthan" parametertype="int" resultmap="productresultmap">
select * from product where sales > #{sales}
</select>
</mapper>控制器类:
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
import java.util.list;
@restcontroller
@requestmapping("/api/products")
public class productcontroller {
@autowired
private productmapper productmapper;
@getmapping("/")
public list<product> getallproducts() {
return productmapper.findall();
}
@postmapping("/")
public int addproduct(@requestbody product product) {
return productmapper.insert(product);
}
@getmapping("/top-selling")
public list<product> gettopsellingproducts(@requestparam int topn) {
list<product> products = productmapper.findbysalesgreaterthan(0);
products.sort((p1, p2) -> p2.getsales() - p1.getsales());
if (products.size() > topn) {
return products.sublist(0, topn);
}
return products;
}
}测试类:
import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import java.util.list;
import static org.junit.jupiter.api.assertions.assertequals;
@springboottest
class productapplicationtests {
@autowired
private productcontroller productcontroller;
@test
void contextloads() {
}
@test
void testgetallproducts() {
list<product> products = productcontroller.getallproducts();
assertequals(5, products.size());
}
@test
void testaddproduct() {
product product = new product("p006", "平板", 2000.0, 70);
int count = productcontroller.addproduct(product);
assertequals(1, count);
}
@test
void testgettopsellingproducts() {
list<product> topsellingproducts = productcontroller.gettopsellingproducts(3);
assertequals(3, topsellingproducts.size());
assertequals("p004", topsellingproducts.get(0).getproductid());
assertequals("p005", topsellingproducts.get(1).getproductid());
assertequals("p001", topsellingproducts.get(2).getproductid());
}
}✅ 结论:集成mybatis的步骤包括添加mybatis依赖、配置mybatis连接信息、创建实体类、创建mapper接口、创建mapper xml文件、创建控制器类、测试应用。
18.6 spring boot与jpa的集成
spring boot与jpa的集成是常用的数据访问方法之一。
18.6.1 集成jpa的步骤
定义:集成jpa的步骤是指使用spring boot与jpa集成的方法。
步骤:
- 在pom.xml文件中添加jpa依赖。
- 在application.properties或application.yml文件中配置jpa连接信息。
- 创建实体类。
- 创建repository接口。
- 创建控制器类。
- 测试应用。
示例:
pom.xml文件中的jpa依赖:
<dependencies>
<!-- web依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<!-- data jpa依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-jpa</artifactid>
</dependency>
<!-- mysql依赖 -->
<dependency>
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
<scope>runtime</scope>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-test</artifactid>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的jpa连接信息:
# 服务器端口 server.port=8080 # 数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf-8&usessl=false&servertimezone=utc spring.datasource.driver-class-name=com.mysql.cj.jdbc.driver spring.datasource.username=root spring.datasource.password=123456 # jpa配置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
实体类、repository接口、控制器类、测试类与集成mysql的示例相同。
✅ 结论:集成jpa的步骤包括添加jpa依赖、配置jpa连接信息、创建实体类、创建repository接口、创建控制器类、测试应用。
18.7 spring boot的事务管理
spring boot的事务管理是数据访问的重要组件。
18.7.1 事务管理的定义
定义:事务管理是指使用spring boot进行事务处理的方法。
作用:
- 保证数据的一致性。
- 保证数据的完整性。
- 保证数据的原子性。
常用注解:
- @transactional:标记方法或类为事务方法。
示例:
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional;
import java.util.list;
@service
public class productservice {
@autowired
private productrepository productrepository;
@transactional
public void addproduct(product product) {
productrepository.save(product);
}
@transactional
public void updateproduct(product product) {
productrepository.save(product);
}
@transactional
public void deleteproduct(long id) {
productrepository.deletebyid(id);
}
@transactional(readonly = true)
public list<product> getallproducts() {
return productrepository.findall();
}
@transactional(readonly = true)
public list<product> gettopsellingproducts(int topn) {
list<product> products = productrepository.findbysalesgreaterthan(0);
products.sort((p1, p2) -> p2.getsales() - p1.getsales());
if (products.size() > topn) {
return products.sublist(0, topn);
}
return products;
}
}✅ 结论:事务管理是指使用spring boot进行事务处理的方法,常用注解包括@transactional。
18.8 spring boot的实际应用场景
在实际开发中,spring boot数据访问与数据库集成的应用场景非常广泛,如:
- 实现商品的展示与购买。
- 实现订单的管理。
- 实现用户的管理。
- 实现博客的发布与管理。
示例:
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.data.jpa.repository.jparepository;
import org.springframework.stereotype.repository;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional;
import org.springframework.web.bind.annotation.*;
import javax.persistence.*;
import java.util.list;
// 产品类
@entity
@table(name = "product")
public class product {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string productid;
private string productname;
private double price;
private int sales;
public product() {
}
public product(string productid, string productname, double price, int sales) {
this.productid = productid;
this.productname = productname;
this.price = price;
this.sales = sales;
}
// getter和setter方法
public long getid() {
return id;
}
public void setid(long id) {
this.id = id;
}
public string getproductid() {
return productid;
}
public void setproductid(string productid) {
this.productid = productid;
}
public string getproductname() {
return productname;
}
public void setproductname(string productname) {
this.productname = productname;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
public int getsales() {
return sales;
}
public void setsales(int sales) {
this.sales = sales;
}
@override
public string tostring() {
return "product{" +
"id=" + id +
", productid='" + productid + '\'' +
", productname='" + productname + '\'' +
", price=" + price +
", sales=" + sales +
'}';
}
}
// 产品repository
@repository
public interface productrepository extends jparepository<product, long> {
list<product> findbysalesgreaterthan(int sales);
}
// 产品service
@service
public class productservice {
@autowired
private productrepository productrepository;
@transactional
public void addproduct(product product) {
productrepository.save(product);
}
@transactional
public void updateproduct(product product) {
productrepository.save(product);
}
@transactional
public void deleteproduct(long id) {
productrepository.deletebyid(id);
}
@transactional(readonly = true)
public list<product> getallproducts() {
return productrepository.findall();
}
@transactional(readonly = true)
public list<product> gettopsellingproducts(int topn) {
list<product> products = productrepository.findbysalesgreaterthan(0);
products.sort((p1, p2) -> p2.getsales() - p1.getsales());
if (products.size() > topn) {
return products.sublist(0, topn);
}
return products;
}
}
// 产品控制器
@restcontroller
@requestmapping("/api/products")
public class productcontroller {
@autowired
private productservice productservice;
@getmapping("/")
public list<product> getallproducts() {
return productservice.getallproducts();
}
@postmapping("/")
public void addproduct(@requestbody product product) {
productservice.addproduct(product);
}
@putmapping("/{id}")
public void updateproduct(@pathvariable long id, @requestbody product product) {
product.setid(id);
productservice.updateproduct(product);
}
@deletemapping("/{id}")
public void deleteproduct(@pathvariable long id) {
productservice.deleteproduct(id);
}
@getmapping("/top-selling")
public list<product> gettopsellingproducts(@requestparam int topn) {
return productservice.gettopsellingproducts(topn);
}
}
// 应用启动类
@springbootapplication
public class productapplication {
public static void main(string[] args) {
springapplication.run(productapplication.class, args);
}
@autowired
private productservice productservice;
public void run(string... args) {
// 初始化数据
productservice.addproduct(new product("p001", "手机", 1000.0, 100));
productservice.addproduct(new product("p002", "电脑", 5000.0, 50));
productservice.addproduct(new product("p003", "电视", 3000.0, 80));
productservice.addproduct(new product("p004", "手表", 500.0, 200));
productservice.addproduct(new product("p005", "耳机", 300.0, 150));
}
}
// 测试类
@springboottest
class productapplicationtests {
@autowired
private productcontroller productcontroller;
@test
void contextloads() {
}
@test
void testgetallproducts() {
list<product> products = productcontroller.getallproducts();
assertequals(5, products.size());
}
@test
void testaddproduct() {
product product = new product("p006", "平板", 2000.0, 70);
productcontroller.addproduct(product);
list<product> products = productcontroller.getallproducts();
assertequals(6, products.size());
}
@test
void testupdateproduct() {
product product = new product("p001", "手机", 1500.0, 120);
productcontroller.updateproduct(1l, product);
list<product> products = productcontroller.getallproducts();
assertequals(1500.0, products.get(0).getprice());
}
@test
void testdeleteproduct() {
productcontroller.deleteproduct(2l);
list<product> products = productcontroller.getallproducts();
assertequals(4, products.size());
}
@test
void testgettopsellingproducts() {
list<product> topsellingproducts = productcontroller.gettopsellingproducts(3);
assertequals(3, topsellingproducts.size());
assertequals("p004", topsellingproducts.get(0).getproductid());
assertequals("p005", topsellingproducts.get(1).getproductid());
assertequals("p001", topsellingproducts.get(2).getproductid());
}
}输出结果:
- 访问http://localhost:8080/api/products/:
[{"id":1,"productid":"p001","productname":"手机","price":1500.0,"sales":120},{"id":3,"productid":"p003","productname":"电视","price":3000.0,"sales":80},{"id":4,"productid":"p004","productname":"手表","price":500.0,"sales":200},{"id":5,"productid":"p005","productname":"耳机","price":300.0,"sales":150},{"id":6,"productid":"p006","productname":"平板","price":2000.0,"sales":70}] - 访问http://localhost:8080/api/products/top-selling?topn=3:
[{"id":4,"productid":"p004","productname":"手表","price":500.0,"sales":200},{"id":5,"productid":"p005","productname":"耳机","price":300.0,"sales":150},{"id":1,"productid":"p001","productname":"手机","price":1500.0,"sales":120}]
✅ 结论:在实际开发中,spring boot数据访问与数据库集成的应用场景非常广泛,需要根据实际问题选择合适的数据访问方法。
总结
本章我们学习了spring boot数据访问与数据库集成,包括spring boot数据访问的基本方法、spring boot与mysql的集成、spring boot与h2的集成、spring boot与mybatis的集成、spring boot与jpa的集成、spring boot的事务管理、spring boot的实际应用场景,学会了在实际开发中处理数据库访问问题。其中,spring boot数据访问的基本方法、spring boot与mysql的集成、spring boot与h2的集成、spring boot与mybatis的集成、spring boot与jpa的集成、spring boot的事务管理、spring boot的实际应用场景是本章的重点内容。从下一章开始,我们将学习spring boot的其他组件、微服务等内容。
到此这篇关于spring boot 数据访问与数据库集成的文章就介绍到这了,更多相关springboot数据访问和数据库集成内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论