springboot整合Mybatis、JPA、Redis的示例代碼
引言
在springboot 項(xiàng)目中,我們是用ORM 框架來(lái)操作數(shù)據(jù)庫(kù)變的非常方便。下面我們分別整合mysql ,spring data jpa 以及redis 。讓我們感受下快車道。
我們首先創(chuàng)建一個(gè)springboot 項(xiàng)目,創(chuàng)建好之后,我們來(lái)一步步的實(shí)踐。
使用mybatis
引入依賴:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
增加配置
application.properties 中增加連接數(shù)據(jù)庫(kù)的配置。
# Mysql數(shù)據(jù)庫(kù)連接配置 : com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false spring.datasource.username=root spring.datasource.password=123456
創(chuàng)建sql
接下來(lái),我們創(chuàng)建sql 語(yǔ)句。方便我們后面測(cè)試吧。
# 創(chuàng)建數(shù)據(jù)庫(kù)
CREATE DATABASE springbootdata;
# 選擇使用數(shù)據(jù)庫(kù)
USE springbootdata;
# 創(chuàng)建表t_article并插入相關(guān)數(shù)據(jù)
DROP TABLE IF EXISTS t_article;
CREATE TABLE t_article (
id int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
title varchar(200) DEFAULT NULL COMMENT '文章標(biāo)題',
content longtext COMMENT '文章內(nèi)容',
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO t_article VALUES ('1', 'Spring Boot基礎(chǔ)入門', '從入門到精通講解...');
INSERT INTO t_article VALUES ('2', 'Spring Cloud基礎(chǔ)入門', '從入門到精通講解...');
# 創(chuàng)建表t_comment并插入相關(guān)數(shù)據(jù)
DROP TABLE IF EXISTS t_comment;
CREATE TABLE t_comment (
id int(20) NOT NULL AUTO_INCREMENT COMMENT '評(píng)論id',
content longtext COMMENT '評(píng)論內(nèi)容',
author varchar(200) DEFAULT NULL COMMENT '評(píng)論作者',
a_id int(20) DEFAULT NULL COMMENT '關(guān)聯(lián)的文章id',
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO t_comment VALUES ('1', '很全、很詳細(xì)', 'luccy', '1');
INSERT INTO t_comment VALUES ('2', '贊一個(gè)', 'tom', '1');
INSERT INTO t_comment VALUES ('3', '很詳細(xì)', 'eric', '1');
INSERT INTO t_comment VALUES ('4', '很好,非常詳細(xì)', '張三', '1');
INSERT INTO t_comment VALUES ('5', '很不錯(cuò)', '李四', '2');
創(chuàng)建實(shí)體
再接下來(lái),我們需要?jiǎng)?chuàng)建 一個(gè)實(shí)體類,我們就創(chuàng)建一個(gè) t_comment 表對(duì)應(yīng)的實(shí)體類吧。
public class Comment {
private Integer id; //評(píng)論id
private String content; //評(píng)論內(nèi)容
private String author; //評(píng)論作者
private Integer aId; //外鍵:表示當(dāng)前這條評(píng)論是屬于那篇文章
//getter()/setter()
創(chuàng)建mapper
上面都做好后,我們當(dāng)然是來(lái)創(chuàng)建一個(gè)mapper 接口,來(lái)操作數(shù)據(jù)庫(kù)啦,這里我們來(lái)一個(gè)最簡(jiǎn)單的,使用注解的方式。
//標(biāo)識(shí)該接口是mybatis的接口文件,并且讓springboot能夠掃描到該接口,生成該接口的代理對(duì)象,存到容器中
@Mapper
public interface CommentMapper {
//根據(jù)id查詢對(duì)應(yīng)評(píng)論信息
@Select("select * from t_comment where id = #{id}")
Comment findById(Integer id);
}
創(chuàng)建測(cè)試
上面這樣其實(shí)就已經(jīng)完成了springboot 與mybatis 的整合,我們接下來(lái)測(cè)試一下。
在pom.xml 文件中引入:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <scope>test</scope> </dependency>
在測(cè)試類中編寫(xiě):
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootQuickstartApplicationTests {
@Autowired
private CommentMapper commentMapper;
@Test
void contextLoads() {
Comment comment = commentMapper.findById(1);
System.out.println(comment);
}
}
效果:

證明整合mybatis 是成功的。是不是很簡(jiǎn)單,只用引入一個(gè)starter 就可以正常使用mybatis 的功能。
基于xml 方式
上面的是基于注解的,我們也可以基于xml。我們?cè)趍apper 中不寫(xiě)sql ,而放到xml 中編寫(xiě)。這里 ArticleMapper 為例
@Mapper
public interface ArticleMapper {
//根據(jù)id查詢對(duì)應(yīng)的文章
public Article selectArticle(Integer id);
}
對(duì)應(yīng)的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="cn.quellanan.springbootquickstart.mapper.ArticleMapper">
<select id="selectArticle" parameterType="int" resultType="article">
select * from t_article where id = #{id}
</select>
</mapper>
這里我們需要在配置文件中指定我們mapper.xml 的位置,如果不指定,就需要和mapper 同目錄才行。resultType 可以在配置文件中指定別名。
#開(kāi)啟駝峰命名匹配映射mapper mybatis.configuration.map-underscore-to-camel-case=true #配置mybatis的xml映射配置文件路徑 mybatis.mapper-locations=classpath:mapper/*.xml #配置mybatis映射配置文件中實(shí)體類別名 mybatis.type-aliases-package=cn.quellanan.springbootquickstart.pojo
我們?cè)賹?xiě)個(gè)測(cè)試方法測(cè)試下。
@Autowired
private ArticleMapper articleMapper;
@Test
public void selectArticle(){
Article article = articleMapper.selectArticle(1);
System.out.println(article);
}

這樣springboot 整合mybatis 基本的就ok 啦。
使用jpa
上面我們springboot整個(gè)mybatis 需要自己寫(xiě)sql ,接下來(lái)我們偷偷懶,整合一下springData JPA。之前說(shuō)過(guò),springboot data jpa 是一種規(guī)范,必須使用實(shí)現(xiàn)這種規(guī)范的框架,所以前面用了 hibernate 。但是在springboot 中就不用這么麻煩啦,也不用引入 hibernate 相關(guān)的jar .我們也可以使用。下面我們來(lái)看看。
引入依賴
第一步還是需要在pom 文件中引入依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
建立實(shí)體類和表的關(guān)系
引入依賴后,我們需要將實(shí)體類和表以及表屬性建立聯(lián)系。我們還是以 Comment 這個(gè)類。進(jìn)行修改。
@Entity
@Table(name = "t_comment")
public class Comment {
@Id //表明映射主鍵id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; //評(píng)論id
private String content; //評(píng)論內(nèi)容
private String author; //評(píng)論作者
@Column(name = "a_id")
private Integer aId; //外鍵:表示當(dāng)前這條評(píng)論是屬于那篇文章
//getter()/setter()
}
首先需要 @Entity 標(biāo)識(shí)這個(gè)實(shí)體類,可以被處理
@Table() 注解指定數(shù)據(jù)庫(kù)對(duì)應(yīng)的表名
@Id 用來(lái)指定表的主鍵。
@GeneratedValue() 用來(lái)指定主鍵的類型
@Column 用來(lái)指定這個(gè)屬性對(duì)應(yīng)的表的列名,如果類屬性和表列名一致可不指定,不一致就需要指定。
創(chuàng)建一個(gè)接口
我們接下來(lái)創(chuàng)建一個(gè)接口來(lái)使用它,繼承JpaRepository 。有兩個(gè)參數(shù),第一個(gè)參數(shù)是是對(duì)應(yīng)的實(shí)體類對(duì)象,第二個(gè)參數(shù)主鍵數(shù)據(jù)類型。
public interface CommentRepository extends JpaRepository<Comment, Integer> {
}
測(cè)試
接下來(lái),我們就可以進(jìn)行測(cè)試?yán)?/p>
@Autowired
private CommentRepository commentRepository;
@Test
public void selectComment(){
Optional<Comment> byId = commentRepository.findById(1);
System.out.println(byId.get());
}

所以如果不想使用mybatis ,那springboot 整合jpa 也是一種不錯(cuò)的選擇。
使用redis
上面不管是mybatis 還是 springdatajpa 都是基于關(guān)系型數(shù)據(jù)庫(kù)操作的,我們上面操作的就是mysql 數(shù)據(jù)庫(kù)?,F(xiàn)在redis 也經(jīng)常在項(xiàng)目中使用,那springboot 整合使用redis 也很方便。
引入依賴
一樣的,我們首先需要引入依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
配置redis 連接信息
在application.propertis 中增加redis 的相關(guān)配置
#redis服務(wù)器地址 spring.redis.host=127.0.0.1 #redis服務(wù)器連接端口 spring.redis.port=6379 #redis服務(wù)器連接密碼 spring.redis.password=
其實(shí)到現(xiàn)在,我們就已經(jīng)整合好了,可以在項(xiàng)目中操作redis 數(shù)據(jù)庫(kù)啦。
我們來(lái)寫(xiě)一個(gè)測(cè)試方法,分別是插入和查找。
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void insert(){
redisTemplate.opsForValue().set("quellanan","程序員愛(ài)酸奶");
}
@Test
public void select(){
String quellanan = redisTemplate.opsForValue().get("quellanan");
System.out.println(quellanan);
}


可以看到我們直接用的 StringRedisTemplate 。這個(gè)就相當(dāng)于 JdbcTemplate 操作數(shù)據(jù)庫(kù)一樣。兄弟們現(xiàn)在明白了吧,相當(dāng)于是沒(méi)有使用mybatis 或者jpa 這些框架,而是簡(jiǎn)單粗暴的操作數(shù)據(jù)庫(kù)了。
現(xiàn)在很多公司使用數(shù)據(jù)庫(kù)也是直接使用 StringRedisTemplate 或者 RedisTemplate 來(lái)操作的redis 的數(shù)據(jù)庫(kù)的,因?yàn)榛趓edis 的持久層框架還不流行。當(dāng)然我們也可以使用,接下來(lái)我們來(lái)點(diǎn)騷的。
創(chuàng)建一個(gè)實(shí)體類。
@RedisHash(value = "persons") //指定實(shí)體類對(duì)象在redis中的存儲(chǔ)空間
public class Person {
@Id // 用來(lái)標(biāo)識(shí)實(shí)體類主鍵 字符串形式的hashkey標(biāo)識(shí)唯一的實(shí)體類對(duì)象id
private String id;
@Indexed // 用來(lái)標(biāo)識(shí)對(duì)應(yīng)屬性在redis中生成二級(jí)索引
private String firstname;
@Indexed
private String lastname;
private Address address;
}
@RedisHash 用來(lái)指定類的儲(chǔ)存類型,這里使用的的是RedisHash 表示在數(shù)據(jù)庫(kù)中使用hash 存儲(chǔ)。值得注意的是只有@RedisHash 這個(gè)注解來(lái)作用于實(shí)體類上,這個(gè)persons 更像是文件夾,key 的前綴。
@Id 表明主鍵,其實(shí)就是redis 中hash 結(jié)構(gòu)的和前綴組成 key
@Indexed,用來(lái)標(biāo)識(shí)redis 數(shù)據(jù)庫(kù)生成二級(jí)索引,方便條件查詢,一樣的和前綴以及屬性名組成key。
創(chuàng)建一個(gè)接口。
這里繼承的是CrudRepository 。并且也是基于jpa 范式的,感興趣的可以試試。
public interface PersonRepository extends CrudRepository<Person, String> {
// 根據(jù)城市信息查詢對(duì)應(yīng)的人
List<Person> findByAddress_City(String name);
}
測(cè)試方法。
我們接下來(lái),寫(xiě)一個(gè)測(cè)試方法。
@Autowired
private PersonRepository personRepository;
@Test
public void savePerson(){
Person person = new Person();
person.setFirstname("張");
person.setLastname("三");
Address address = new Address();
address.setCity("北京");
address.setCountry("中國(guó)");
person.setAddress(address);
// 向redis數(shù)據(jù)庫(kù)中添加了數(shù)據(jù)
personRepository.save(person);
}
@Test
public void selectPerson(){
List<Person> list = personRepository.findByAddress_City("北京");
for (Person person : list) {
System.out.println(person);
}
}

我們?cè)诳纯磖edis 數(shù)據(jù)庫(kù)。


我們?cè)趤?lái)看下。這些key 都是什么類型存儲(chǔ)的。除了key 為persons:916b5570-5c7f-4a96-b25f-98c9a2f1f43e 是hash 其他的都是set


說(shuō)明我們創(chuàng)建的索引,都是使用set 來(lái)存儲(chǔ)的,并且這些索引只是存放了一個(gè)key 值,也就是我們真正存數(shù)據(jù)的地方。
而 persons:916b5570-5c7f-4a96-b25f-98c9a2f1f43e:idx 存放的是其他索引的key .

這樣我們也可以通過(guò)jpa 這種操作特別是比較負(fù)責(zé)的對(duì)象,我們也能很好的處理啦。
總結(jié)
到這就結(jié)束啦,知道在springboot 中怎么是用mybatis,spring data jpa,redis 就可以啦。
到此這篇關(guān)于springboot整合Mybatis、JPA、Redis的示例代碼的文章就介紹到這了,更多相關(guān)springboot整合Mybatis、JPA、Redis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java selenium Selenium IDE介紹及用法
本文主要介紹java selenium Selenium IDE,這里整理了相關(guān)資料和介紹如何安裝 Selenium IDE和使用方法,有需要的小伙伴可以參考下2016-08-08
SpringBoot?+?Vue?+?ElementUI?實(shí)現(xiàn)?el-table?分頁(yè)功能(詳細(xì)步驟)
本文詳細(xì)介紹了使用SpringBoot和Vue.js結(jié)合ElementUI實(shí)現(xiàn)分頁(yè)功能的數(shù)據(jù)表格,從后端分頁(yè)邏輯到前端展示和狀態(tài)管理,全面解析如何高效處理大量數(shù)據(jù),提升用戶體驗(yàn)與系統(tǒng)性能,感興趣的朋友跟隨小編一起看看吧2024-09-09
SpringBoot快速整合SpringSecurity的詳細(xì)步驟(新手都會(huì)!)
日 Spring Security 是針對(duì)Spring項(xiàng)目的安全框架,也是Spring Boot底層安全模塊默認(rèn)的技術(shù)選型,他可以實(shí)現(xiàn)強(qiáng)大的Web安全控制,下面這篇文章主要給大家介紹了關(guān)于SpringBoot快速整合SpringSecurity的詳細(xì)步驟,需要的朋友可以參考下2023-03-03
使用Spring?Boot進(jìn)行單元測(cè)試詳情
這篇文章主要介紹了使用Spring?Boot進(jìn)行單元測(cè)試詳情,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
數(shù)據(jù)庫(kù)基本操作語(yǔ)法歸納總結(jié)
本篇文章主要介紹了數(shù)據(jù)庫(kù)的一些常用方法及一些基本操作,需要的朋友可以參考下2017-04-04
深入分析JAVA 多線程--interrupt()和線程終止方式
這篇文章主要介紹了JAVA 多線程--interrupt()和線程終止方式的的相關(guān)資料,文中代碼非常細(xì)致,幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06
解決SpringBoot運(yùn)行Test時(shí)報(bào)錯(cuò):SpringBoot Unable to find
這篇文章主要介紹了SpringBoot運(yùn)行Test時(shí)報(bào)錯(cuò):SpringBoot Unable to find a @SpringBootConfiguration,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10

