初学Springboot(四)
前言
本次来讲一讲Springboot的数据访问问题,分别整合了访问MyBatis与JPA跟Redis
提示:以下是本篇文章正文内容,下面案例可供参考
项目目录

首先要知道对应的依赖启动器有哪些
| 名称 | 对应数据库 |
|---|---|
| spring-boot-starter-data-jpa | •Spring Data JPA •Hibernate |
| spring-boot-starter-data-mongodb | •MongoDB •Spring Data MongoDB |
| spring-boot-starter-data-neo4j | •Neo4j图数据库 •Spring Data Neo4j |
| spring-boot-starter-data-redis | •Redis |
一、Springboot整合MyBatis
1.数据准备:
创建数据库、数据表并插入一定的数据
这里我们引用了
先开启数据库,这里我用的是MySQL
①首先创建一张springboot的库

CREATE DATABASE springbootdata;
②创建t_article的表并插入数据

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基础入门', '从入门到退出...');
③创建t_comment表,插入数据

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', '很详细', 'pity', '1');
INSERT INTO `t_comment` VALUES ('4', '年轻人真厉害', '李四', '1');
INSERT INTO `t_comment` VALUES ('5', '很不错', '王五', '2');
2.创建项目,引入相应的启动器:
使用Spring Initializr的方式构建项目,选择MySQL和MyBatis依赖,编写实体类。



编写两张表的实体类
public class Comment {
private Integer id;
private String content;
private String author;
private Integer aId;
@Override
public String toString() {
return "Comment{" +
"id=" + id +
", content='" + content + '\'' +
", author='" + author + '\'' +
", aId=" + aId +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getaId() {
return aId;
}
public void setaId(Integer aId) {
this.aId = aId;
}
}
public class Article {
private Integer id;
private String title;
private String content;
private List<Comment> commentList;
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
", commentList=" + commentList +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
}
引入Mybatis依赖启动器
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
增加依赖,以阿里巴巴的Druid数据源为案例
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
3.编写配置文件:
在配置文件中进行数据库连接配置以及进行第三方数据源的默认参数覆盖。
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboottest1?serverTimezone=UTC
spring.datasource.username=你数据库的帐号
spring.datasource.password=你数据库的密码
#对数据源默认值进行修改
#数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始化连接数
spring.datasource.initialSize=20
#最小空闲数
spring.datasource.minIdle=10
#最大连接数
spring.datasource.maxActive=100
#开启驼峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true
方式1:用注解方式整合
优点:相对简洁,但是多表操作的话不方便
这里可以发现,接口只需要添加注解,不用去再创建一个实现类
①创建接口Mapper
package com.itheima.mapper;
import com.demo03.domain.Comment;
import org.apache.ibatis.annotations.*;
@Mapper//表示该类是一个mybatis接口文件,是需要被springboot扫描的
public interface CommentMapper {
//查询方法
@Select("select * from t_comment where id =#{id}")
public Comment findById(Integer id);
//添加方法
@Insert("insert into t_comment values(#{id},#{content},#{author},#{aId})")
public void insertComment(Comment comment);
//修改
@Update("update t_comment set content=#{content} where id=#{id}")
public void updateComment(Comment comment);
//删除
@Delete("delete from t_comment where id=#{id}")
public void deleteComment(Insert id);
}
②创建测试类
@Autowired
private CommentMapper commentMapper;
@Test
void contextLoads() {
Comment comment=commentMapper.findById(1);
System.out.println(comment);
}
方式2:使用配置文件的方式整合MyBatis
优点:文件复杂比较适用(多表查询)
整合步骤:
1.创建Mapper接口文件:ArticleMapper
@Mapper注解
@Mapper
public interface ArticleMapper {
//根据id查询文章(包含对应的评论)
public Article selectArticle(Integer id);
//根据id更新
public Article updateArticle(Article id);
}
2.创建XML映射文件:编写对应的SQL语句

<!--约束头-->
<?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">
<!-- namepace对应接口的程序-->
<mapper namespace="com.demo03.mapper.ArticleMapper">
<!--自定义映射-->
<resultMap id="ac" type="Article">
<!-- property属性名 column字段名-->
<!-- 先id然后result-->
<id property="id" column="id"></id>
<result property="title" column="title"></result>
<result property="content" column="content"></result>
<!-- 如果属性里面是另一个实体类用collection ofType泛型对应实体类路径-->
<collection property="commentList" ofType="com.demo03.domain.Comment">
<id property="id" column="c_id"></id>
<result property="content" column="content"></result>
<result property="author" column="author"></result>
<result property="aId" column="aId"></result>
</collection>
</resultMap>
<!-- id=接口方法名 parameterType对应方法获取的值类型-->
<select id="selectArticle" resultMap="ac" parameterType="int">
SELECT a.*,c.id c_id,c.content c_content,c.author,c.a_Id aId
FROM t_article a,t_comment c
WHERE a.id=c.a_id AND a.id = #{id}
</select>
<update id="updateArticle" parameterType="Article" >
UPDATE t_article
<set>
<if test="title !=null and title !=''">
title=#{title},
</if>
<if test="content !=null and content !=''">
content=#{content}
</if>
</set>
WHERE id=#{id}
</update>
</mapper>
3.在全局文件中配置XML映射文件路径以及实体类别名映射路径
#开启驼峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true
#配置mybatis的xml配置文件路径(如果有多个配置文件可以把Att.xml改为*.xml)
mybatis.mapper-locations=classpath:mapper/*.xml
#配置xml映射文件中指定的实体类别名路径
mybatis.type-aliases-package=com.demo03.domain
4.编写测试方法进行接口方法测试及整合测试
private ArticleMapper articleMapper;
@Test
void contextLoads2() {
根据id查询文章(包含对应的评论)
Article article=articleMapper.selectArticle(2);
System.out.println(article);
}
二.Spring Boot 整合JPA
Spring Data JPA是Spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架,它提供了增删改查等常用功能,使开发者可以用较少的代码实现数据操作,同时还易于扩展。
总结:创建一个实体类与表进行关联映射,创建一个接口继承JpaRepository并额外编写sql语句
1.在pom中添加Jpa依赖启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
步骤一:建立一个实体类,表示与表的映射关系
@GeneratedValue(strategy = GenerationType.IDENTITY)
这个后缀的各个作用
IDENTITY主键生成自增长
AUTO根据底层数据库判断生成策略
SEQUENCE是oulikou库数据库
TABLE表的形式我们取主键是从表中取
@Column(name = “content”)//对应表中的字段关系映射
@Entity(name= "t_comment") //该注解表示当前实体类是与表有映射关系的实体类
public class Discuss {
@Id//该注解表示配置该属性对应的字段为主键
//IDENTITY主键生成自增长
// AUTO根据底层数据库判断生成策略
// SEQUENCE是oulikou库数据库
// TABLE表的形式我们取主键是从表中取
@GeneratedValue(strategy = GenerationType.IDENTITY)
//主键生成策略
private Integer id;
@Column(name = "content")
private String content;
@Column(name = "author")
private String author;
@Column(name = "a_Id")
private Integer aId;
@Override
public String toString() {
return "Discuss{" +
"id=" + id +
", content='" + content + '\'' +
", author='" + author + '\'' +
", aId=" + aId +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getaId() {
return aId;
}
public void setaId(Integer aId) {
this.aId = aId;
}
}
步骤二:编写接口类
DiscussRepository
新增注解:@Transactional//进行数控(数据变动要加)
•在自定义的Repository接口中,针对数据的变更操作(修改、删除),无论是否使用了@Query注解,都必须在方法上方添加@Transactional注解进行事务管理,否则程序执行就会出现InvalidDataAccessApiUsageException异常。
•如果在调用Repository接口方法的业务层Service类上已经添加了@Transactional注解进行事务管理,那么Repository接口文件中就可以省略@Transactional注解
@Modifying//对数据库进行变更必须加
•在自定义的Repository接口中,使用@Query注解方式执行数据变更操作(修改、删除),除了要使用@Query注解,还必须添加@Modifying注解表示数据变更。
@Query("")//添加sql语句
例子:@Query(“UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2”)
public int updateDiscuss(String author,Integer id);
?1表示下面方法的第一个对象 ?2表示第二个
对应导包
import com.demo03.domain.Discuss;
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 javax.transaction.Transactional;
接口类DiscussRepository
//当前操作的<实体类,主键数据类型>
//好处:具有简单的增删查改功能
public interface DiscussRepository extends JpaRepository<Discuss,Integer> {
// 1查询author非空的Discuss评论信息
//使用jpa方式
//findBy+查询条件+查询方式
public List<Discuss> findByAuthorNotNull();
//2通过文章id分页查询出Discuss评论信息。
//用注解引入sql语句
@Query("SELECT c FROM t_comment c WHERE c.aId = ?1")
public List<Discuss> getDiscussPaged(Integer aid, Pageable pageable);
//3通过文章id分页查询出Discuss评论信息。
//nativeQuery使用原生sql语句例如上面的语句c可以不用加*
@Query(value = "SELECT * FROM t_comment WHERE a_Id = ?1",nativeQuery = true)
public List<Discuss> getDiscussPaged2(Integer aid,Pageable pageable);
//4对数据进行更新
@Transactional//进行数控
@Modifying//对数据库进行变更必须加
@Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")
public int updateDiscuss(String author,Integer id);
//5删除操作
@Transactional
@Modifying
@Query("DELETE from t_comment c WHERE c.id = ?1")
public int deleteDiscuss(Integer id);
}
步骤三:测试类
@Autowired
private DiscussRepository discussRepository;
@Test
public void test1(){
// 查询crudrespoitory自带的方法
//Optional<T>是在java.util包下的一个用于代替null的一个工具类
Optional<Discuss> byId= discussRepository.findById(1);
//调用类里面的get方法,如果为空回会输出,解决空指针异常
System.out.println(byId.get());
}
@Test
public void test2(){
// 查询根据名字的方法
List<Discuss> ByAuthorNotNull= discussRepository.findByAuthorNotNull();
for (Discuss discuss:ByAuthorNotNull)
System.out.println(discuss);
}
@Test
public void test3(){
// 查询自带的方法
int i= discussRepository.deleteDiscuss(1);
System.out.println(i);
}
三.Spring Boot 整合Redis
Redis 是一个开源(BSD许可)的、内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,并提供多种语言的API。
Redis优点
1.存取速度快:Redis速度非常快,每秒可执行大约110000次的设值操作,或者执行81000次的读取操作。
2.支持丰富的数据类型:Redis支持开发人员常用的大多数数据类型,例如列表、集合、排序集和散列等。(字符串,List,哈希)
3.操作具有原子性:所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新后的值。
4.提供多种功能:Redis提供了多种功能特性,可用作非关系型数据库、缓存中间件、消息中间件等。
1.在pom文件中添加Spring Data Redis依赖启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.编写ORM实体类
记得要生成getset方法
Person实体类
@RedisHash("persons")//创建一个存储空间
public class Person {
@Id//实体类主键
private String id;
@Indexed//用户标识该属性回在redis数据库中生成二级索引
private String firstname;
@Indexed
private String lastname;
private Address address;
private List<Family> familyList;
}
Address实体类
public class Address {
@Indexed
private String city;
@Indexed
private String country;
}
Family实体类
public class Family {
@Indexed
private String type;
@Indexed
private String username;
}
3.编写Repository接口
创建一个接口PersonRepository
public interface PersonRepository extends CrudRepository<Person,String> {
//根据姓名查询某人
List<Person> findByLastname(String lastname);
//根据姓氏查询某人(加了分页查询)
Page<Person> findPersonByLastname(String lastname, Pageable page);
//根据姓和名查询某人
List<Person> findByFirstnameAndLastname(String firstname, String lastname);
//查询这座城市查询
List<Person> findByAddress_City(String city);
//根据家庭查人
List<Person> findByFamilyList_Username(String username);
}
4.在全局配置文件application.properties中添加Redis数据库连接配置
#配置redis连接
#配置服务器地址
spring.redis.host=127.0.0.1
#redis连接端口
spring.redis.port=6379
#redis服务连接密码
spring.redis.password=
5.编写单元测试进行接口方法测试及整合测试
@SpringBootTest
class RedisTest {
@Autowired
private PersonRepository personRepository;
@Test
public void savePerson(){
Person person=new Person();
person.setFirstname("有才");
person.setLastname("张");
Address address = new Address();
address.setCity("北京");
person.setAddress(address);
Family family = new Family();
family.setType("父亲");
family.setUsername("张三");
Family family2 = new Family();
family.setType("母亲");
family.setUsername("李四");
ArrayList<Family> familes = new ArrayList<>();
familes.add(family);
familes.add(family2);
person.setFamilyList(familes);
personRepository.save(person);
}
@Test
public void findByLastname(){
List<Person> zhang = personRepository.findByLastname("张");
System.out.println(zhang);
}
}
进入Redis可视化工具查看对应插入的数据
总结
相关文章
初学Springboot(一)
初学Springboot(二)
初学Springboot(三)
本章是对Springboot数据的整合,这里就MyBatis,JPA,REdis进行数据整合
用了三个案例进行运行测试