springboot整合Mybatis、JPA、Redis的示例代碼
引言
在springboot 項目中,我們是用ORM 框架來操作數(shù)據(jù)庫變的非常方便。下面我們分別整合mysql ,spring data jpa 以及redis 。讓我們感受下快車道。
我們首先創(chuàng)建一個springboot 項目,創(chuàng)建好之后,我們來一步步的實踐。
使用mybatis
引入依賴:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
增加配置
application.properties 中增加連接數(shù)據(jù)庫的配置。
# Mysql數(shù)據(jù)庫連接配置 : 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
接下來,我們創(chuàng)建sql 語句。方便我們后面測試吧。
# 創(chuàng)建數(shù)據(jù)庫
CREATE DATABASE springbootdata;
# 選擇使用數(shù)據(jù)庫
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 '文章標題',
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 '評論id',
content longtext COMMENT '評論內(nèi)容',
author varchar(200) DEFAULT NULL COMMENT '評論作者',
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', '很全、很詳細', 'luccy', '1');
INSERT INTO t_comment VALUES ('2', '贊一個', 'tom', '1');
INSERT INTO t_comment VALUES ('3', '很詳細', 'eric', '1');
INSERT INTO t_comment VALUES ('4', '很好,非常詳細', '張三', '1');
INSERT INTO t_comment VALUES ('5', '很不錯', '李四', '2');
創(chuàng)建實體
再接下來,我們需要創(chuàng)建 一個實體類,我們就創(chuàng)建一個 t_comment 表對應(yīng)的實體類吧。
public class Comment {
private Integer id; //評論id
private String content; //評論內(nèi)容
private String author; //評論作者
private Integer aId; //外鍵:表示當(dāng)前這條評論是屬于那篇文章
//getter()/setter()
創(chuàng)建mapper
上面都做好后,我們當(dāng)然是來創(chuàng)建一個mapper 接口,來操作數(shù)據(jù)庫啦,這里我們來一個最簡單的,使用注解的方式。
//標識該接口是mybatis的接口文件,并且讓springboot能夠掃描到該接口,生成該接口的代理對象,存到容器中
@Mapper
public interface CommentMapper {
//根據(jù)id查詢對應(yīng)評論信息
@Select("select * from t_comment where id = #{id}")
Comment findById(Integer id);
}
創(chuàng)建測試
上面這樣其實就已經(jīng)完成了springboot 與mybatis 的整合,我們接下來測試一下。
在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>
在測試類中編寫:
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootQuickstartApplicationTests {
@Autowired
private CommentMapper commentMapper;
@Test
void contextLoads() {
Comment comment = commentMapper.findById(1);
System.out.println(comment);
}
}
效果:

證明整合mybatis 是成功的。是不是很簡單,只用引入一個starter 就可以正常使用mybatis 的功能。
基于xml 方式
上面的是基于注解的,我們也可以基于xml。我們在mapper 中不寫sql ,而放到xml 中編寫。這里 ArticleMapper 為例
@Mapper
public interface ArticleMapper {
//根據(jù)id查詢對應(yīng)的文章
public Article selectArticle(Integer id);
}
對應(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 可以在配置文件中指定別名。
#開啟駝峰命名匹配映射mapper mybatis.configuration.map-underscore-to-camel-case=true #配置mybatis的xml映射配置文件路徑 mybatis.mapper-locations=classpath:mapper/*.xml #配置mybatis映射配置文件中實體類別名 mybatis.type-aliases-package=cn.quellanan.springbootquickstart.pojo
我們再寫個測試方法測試下。
@Autowired
private ArticleMapper articleMapper;
@Test
public void selectArticle(){
Article article = articleMapper.selectArticle(1);
System.out.println(article);
}

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

所以如果不想使用mybatis ,那springboot 整合jpa 也是一種不錯的選擇。
使用redis
上面不管是mybatis 還是 springdatajpa 都是基于關(guān)系型數(shù)據(jù)庫操作的,我們上面操作的就是mysql 數(shù)據(jù)庫?,F(xiàn)在redis 也經(jī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=
其實到現(xiàn)在,我們就已經(jīng)整合好了,可以在項目中操作redis 數(shù)據(jù)庫啦。
我們來寫一個測試方法,分別是插入和查找。
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void insert(){
redisTemplate.opsForValue().set("quellanan","程序員愛酸奶");
}
@Test
public void select(){
String quellanan = redisTemplate.opsForValue().get("quellanan");
System.out.println(quellanan);
}


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

我們在看看redis 數(shù)據(jù)庫。


我們在來看下。這些key 都是什么類型存儲的。除了key 為persons:916b5570-5c7f-4a96-b25f-98c9a2f1f43e 是hash 其他的都是set


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

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

