在开发中,通常会涉及到对数据库的数据进行操作,Spring Boot在简化项目开发以及实现自动化配置的基础上,对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持。
Spring Boot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。
USE `springbootdata`;
CREATE TABLE `t_article` (
`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
`title` varchar(200) DEFAULT NULL COMMENT '文章标题',
`content` longtext COMMENT '文章内容',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
CREATE TABLE `t_comment` (
`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
`content` longtext COMMENT '评论内容',
`author` varchar(200) DEFAULT NULL COMMENT '评论作者',
`a_id` int(20) DEFAULT NULL COMMENT '关联的文章id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '狂奔的蜗牛', '1');
INSERT INTO `t_comment` VALUES ('2', '赞一个', 'tom', '1');
INSERT INTO `t_comment` VALUES ('3', '很详细', 'kitty', '1');
INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '张三', '1');
INSERT INTO `t_comment` VALUES ('5', '很不错', '张杨', '2');
好处是程序启动时自动创建数据库数据表。
参考:Spring实战(第5版) - 3.1 使用JDBC读取和写入数据
Spring Boot 使用 H2 数据库的控制台(Console)_h2 console-CSDN博客
在resources下创建如下两个文件:
schema.sql
CREATE TABLE if not exists `t_article` (
`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
`title` varchar(200) DEFAULT NULL COMMENT '文章标题',
`content` longtext COMMENT '文章内容',
PRIMARY KEY (`id`)
);
CREATE TABLE if not exists `t_comment` (
`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
`content` longtext COMMENT '评论内容',
`author` varchar(200) DEFAULT NULL COMMENT '评论作者',
`a_id` int(20) DEFAULT NULL COMMENT '关联的文章id',
PRIMARY KEY (`id`)
);
data.sql
delete from t_article;
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
delete from t_comment;
INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '狂奔的蜗牛', '1');
INSERT INTO `t_comment` VALUES ('2', '赞一个', 'tom', '1');
INSERT INTO `t_comment` VALUES ('3', '很详细', 'kitty', '1');
INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '张三', '1');
INSERT INTO `t_comment` VALUES ('5', '很不错', '张杨', '2');
引入依赖:
com.h2database
h2
runtime
org.springframework.boot
spring-boot-starter-data-jpa
配置:spring.datasource.url=jdbc:h2:mem:springbootdata
查看数据库:http://localhost:8080/h2-console
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.2
mysql
mysql-connector-java
public class Comment {
private Integer id;
private String content;
private String author;
private Integer aId;
//添加set 、get、 toString
}
public class Article {
private Integer id;
private String title;
private String content;
private List commentList;
//添加set 、get、 toString
}
导入Druid对应的starter:
com.alibaba
druid-spring-boot-starter
1.2.16
在application.properties中添加数据库连接配置和第三方数据源配置
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.initialSize=20
spring.datasource.druid.minIdle=10
spring.datasource.druid.maxActive=100
测试是否整合成功
@Autowired
private DruidDataSource dataSource;
@Test
public void testDruidDataSource() {
System.out.println(dataSource.getMaxActive());
}
com.itheima.mapper
@Mapper
public interface CommentMapper {
@Select("SELECT * FROM t_comment WHERE id =#{id}")
public Comment findById(Integer id);
@Insert("INSERT INTO t_comment(content,author,a_id) " +
"values (#{content},#{author},#{aId})")
public int insertComment(Comment comment);
@Update("UPDATE t_comment SET content=#{content} WHERE id=#{id}")
public int updateComment(Comment comment);
@Delete("DELETE FROM t_comment WHERE id=#{id}")
public int deleteComment(Integer id);
}
提示:如果接口文件过多,可以在启动类上添加@MapperScan(“接口文件所在的包名”),不必再接口文件上添加@Mapper.
控制台显示SQL:
logging.level.你的Mapper包=日志等级
例如:logging.level.com.itheima.myblog.mapper=debug
@Autowired
//会报错,但不影响执行,可以在Mapper接口中添加//@Component(“commentMapper”)
private CommentMapper commentMapper;
@Test
public void selectComment() {
Comment comment = commentMapper.findById(1);
System.out.println(comment);
}
关联对象没有查询出来,如下图
原因:实体类叫aId,数据表叫a_id,名称不一致,导致映射不成功。
解决方法:因为aId按驼峰命名的,所以开启驼峰命名匹配映射 mybatis.configuration.map-underscore-to-camel-case=true
@Mapper
public interface ArticleMapper {
public Article selectArticle(Integer id);
public int updateArticle(Article article);
}
创建文件夹mapper,不是资源文件夹,如下图
UPDATE t_article
title=#{title},
content=#{content}
WHERE id=#{id}
#配置MyBatis的xml配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#设置XML映射文件中的实体类别名的路径
mybatis.type-aliases-package=com.itheima.domain
@Autowired
private ArticleMapper articleMapper;
@Test
public void selectArticle() {
Article article = articleMapper.selectArticle(1);
System.out.println(article);
}
Spring Data JPA是Spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架,它提供了增删改查等常用功能,使开发者可以用较少的代码实现数据操作,同时还易于扩展。
server.port=8088
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=zptc1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto
是 Spring Boot 应用程序中与 JPA(Java Persistence API)和 Hibernate 相关的配置属性。Hibernate 是一个流行的 JPA 实现,用于将 Java 对象映射到关系数据库中的表。
ddl-auto
属性用于控制 Hibernate 在启动时如何自动处理数据库架构(DDL,即数据定义语言)。具体来说,它定义了 Hibernate 是否应该基于实体类自动创建、更新或验证数据库表结构。
以下是 ddl-auto
的几个常用值:
create
的基础上,当 Hibernate 的 SessionFactory 关闭时,它会删除所有创建的表。这同样适用于开发或测试环境。注意:尽管 ddl-auto
在开发过程中可能非常方便,但在生产环境中使用它通常是不推荐的。在生产环境中,建议使用迁移工具(如 Flyway 或 Liquibase)来管理数据库架构的版本控制。这样可以确保架构更改的清晰、可预测和可审计。
org.springframework.boot
spring-boot-starter-data-jpa
com.mysql
mysql-connector-j
runtime
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity(name = "t_comment")
public class Discuss {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String content;
private String author;
@Column(name = "a_id")
private Integer aId;
//补上get、set、toString方法
}
自定义Repository接口,必须继承XXRepository
Repository继承关系如下:
CrudRepository
在Spring Data JPA中,CrudRepository
是一个接口,它提供了基本的 CRUD(创建、读取、更新、删除)操作。虽然 CrudRepository
并没有直接提供一个专门用于更新的方法,但你可以通过 save()
方法来实现更新的功能。
当你调用 save()
方法并传递一个实体对象时,Spring Data JPA 会检查该实体是否已经存在于数据库中(通常是通过主键来判断,所以实体对象设置了主键值时会出现一条查询语句)。
save()
方法会创建一个新的记录。save()
方法会更新该实体的状态。使用Spring Data JPA进行数据操作的多种实现方式
1、如果自定义接口继承了JpaRepository接口,则默认包含了一些常用的CRUD方法。
2、自定义Repository接口中,可以使用@Query注解配合SQL语句进行数据的查、改、删操作。
3、自定义Repository接口中,可以直接使用关键字构成的方法名进行查询操作。
查询方法定义规范
简单查询条件 :查询某一个实体类或是集合
在Repository 子接口中声明方法:
①、不是随便声明的,而需要符合一定的规范
②、查询方法以 find | read | get 开头
③、涉及条件查询时,条件的属性用条件关键字连接
④、要注意的是:条件属性以首字母大写
⑤、支持属性的级联查询。若当前类有符合条件的属性,则优先使用,而不使用级联属性。若需要使用级联属性,则属性之间使用_连接
@Transactional注解
变更操作,要配合使用@Query与Modify注解
使用Example实例进行复杂条件查询
创建子包repository,及接口DiscussRepository
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
public interface DiscussRepository extends JpaRepository{
//查询author非空的Discuss评论信息
public List findByAuthorNotNull();
//通过文章id分页查询出Discuss评论信息。JPQL
@Query("SELECT c FROM t_comment c WHERE c.aId = ?1")
public List getDiscussPaged(Integer aid,Pageable pageable);
//通过文章id分页查询出Discuss评论信息。原生sql
@Query(value = "SELECT * FROM t_comment WHERE a_Id = ?1",nativeQuery = true)
public List getDiscussPaged2(Integer aid,Pageable pageable);
//使用命名参数:bb
@Query("SELECT c FROM t_comment c WHERE c.aId = :bb")
public List getDiscussPaged3(@Param(value = "bb") Integer aid,Pageable pageable);
//对数据进行更新和删除操作
@Transactional
@Modifying
@Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")
public int updateDiscuss(String author,Integer id);
@Transactional
@Modifying
@Query("DELETE t_comment c WHERE c.id = ?1")
public int deleteDiscuss(Integer id);
}
注:
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@SpringBootTest
class JpaTests {
@Autowired
private DiscussRepository repository;
//使用JpaRepository内部方法
@Test
public void selectComment() {
Optionaloptional = repository.findById(1);
if (optional.isPresent()) {
System.out.println(optional.get());
}
}
//使用方法名关键字进行数据操作
@Test
public void selectCommentByKeys() {
Listlist = repository.findByAuthorNotNull();
for (Discuss discuss : list) {
System.out.println(discuss);
}
}
//使用@Query注解
@Test
public void selectCommentPaged() {
Pageable page = PageRequest.of(0, 3);
Listlist = repository.getDiscussPaged(1, page);
list.forEach(t -> System.out.println(t));
}
//使用Example封装参数,精确匹配查询条件
@Test
public void selectCommentByExample() {
Discuss discuss=new Discuss();
discuss.setAuthor("张三");
Example example = Example.of(discuss);
List list = repository.findAll(example);
list.forEach(t -> System.out.println(t));
}
//使用ExampleMatcher模糊匹配查询条件
@Test
public void selectCommentByExampleMatcher() {
Discuss discuss=new Discuss();
discuss.setAuthor("张");
ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("author",
ExampleMatcher.GenericPropertyMatcher.of(ExampleMatcher.StringMatcher.CONTAINING));
Example example = Example.of(discuss, matcher);
List list = repository.findAll(example);
System.out.println(list);
}
//保存评论
@Test
public void saveDiscuss() {
Discuss discuss=new Discuss();
discuss.setContent("张某的评论xxxx");
discuss.setAuthor("张某");
Discuss newDiscuss = repository.save(discuss);
System.out.println(newDiscuss);
}
//更新作者
@Test
public void updateDiscuss() {
int i = repository.updateDiscuss("更新者", 1);
System.out.println("discuss:update:"+i);
}
//删除评论
@Test
public void deleteDiscuss() {
int i = repository.deleteDiscuss(7);
System.out.println("discuss:delete:"+i);
}
}
简介:Redis 是一个开源(BSD许可)的、内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,并提供多种语言的API。
优点:
org.springframework.boot
spring-boot-starter-data-redis
@RedisHash("persons") // 指定操作实体类对象在Redis数据库中的存储空间
public class Person {
@Id// 标识实体类主键
private String id;
// 标识对应属性在Redis数据库中生成二级索引,索引名就是属性名,可以方便地进行数据条件查询
@Indexed
private String firstname;
@Indexed
private String lastname;
private Address address;
private ListfamilyList;
public Person() { }
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
//补充get set toString
}
public class Address {
@Indexed
private String city;
@Indexed
private String country;
public Address() {
}
public Address(String city, String country) {
this.city = city;
this.country = country;
}
//补充get set toString
}
public class Family {
@Indexed
private String type;
@Indexed
private String username;
public Family() { }
public Family(String type, String username) {
this.type = type;
this.username = username;
}
//补充get set toString
}
不需要添加spring-boot-starter-data-jpa这个依赖,即:
org.springframework.boot
spring-boot-starter-data-jpa
只要继承CrudRepository即可,如下:
public interface PersonRepository extends CrudRepository {
List findByLastname(String lastname);
Page findPersonByLastname(String lastname, Pageable page);
List findByFirstnameAndLastname(String firstname, String lastname);
List findByAddress_City(String city);
List findByFamilyList_Username(String username);
}
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
@SpringBootTest
public class RedisTests {
@Autowired
private PersonRepository repository;
@Test
public void savePerson() {
Person person =new Person("张","有才");
Person person2 =new Person("James","Harden");
// 创建并添加住址信息
Address address=new Address("北京","China");
person.setAddress(address);
// 创建并添加家庭成员
Listlist =new ArrayList<>();
Family dad =new Family("父亲","张良");
Family mom =new Family("母亲","李香君");
list.add(dad);
list.add(mom);
person.setFamilyList(list);
// 向Redis数据库添加数据
Person save = repository.save(person);
Person save2 = repository.save(person2);
System.out.println(save);
System.out.println(save2);
}
@Test
public void selectPerson() {
Listlist = repository.findByAddress_City("北京");
System.out.println(list);
}
@Test
public void updatePerson() {
Person person = repository.findByFirstnameAndLastname("张","有才").get(0);
person.setLastname("小明");
Person update = repository.save(person);
System.out.println(update);
}
@Test
public void deletePerson() {
Person person = repository.findByFirstnameAndLastname("张","小明").get(0);
repository.delete(person);
}
}