引言
在springboot 項目中,我們是用ORM 框架來操作數據庫變的非常方便。下面我們分別整合mysql ,spring data jpa 以及redis 。讓我們感受下快車道。
我們首先創建一個springboot 項目,創建好之後,我們來一步步的實踐。
使用mybatis
引入依賴:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
增加配置
application.properties 中增加連接數據庫的配置。
# Mysql數據庫連接配置 : 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
創建sql
接下來,我們創建sql 語句。方便我們後面測試吧。
# 創建數據庫
CREATE DATABASE springbootdata;
# 選擇使用數據庫
USE springbootdata;
# 創建表t_article並插入相關數據
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 '文章內容',
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並插入相關數據
DROP TABLE IF EXISTS 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', '很全、很詳細', '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');
創建實體
再接下來,我們需要創建 一個實體類,我們就創建一個 t_comment 表對應的實體類吧。
public class Comment {
private Integer id; //評論id
private String content; //評論內容
private String author; //評論作者
private Integer aId; //外鍵:表示當前這條評論是屬於那篇文章
//getter()/setter()
創建mapper
上面都做好後,我們當然是來創建一個mapper 接口,來操作數據庫啦,這裏我們來一個最簡單的,使用註解的方式。
//標識該接口是mybatis的接口文件,並且讓springboot能夠掃描到該接口,生成該接口的代理對象,存到容器中
@Mapper
public interface CommentMapper {
//根據id查詢對應評論信息
@Select("select * from t_comment where id = #{id}")
Comment findById(Integer id);
}
創建測試
上面這樣其實就已經完成了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 {
//根據id查詢對應的文章
public Article selectArticle(Integer id);
}
對應的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 是一種規範,必須使用實現這種規範的框架,所以前面用了 hibernate 。但是在springboot 中就不用這麼麻煩啦,也不用引入 hibernate 相關的jar .我們也可以使用。下面我們來看看。
引入依賴
第一步還是需要在pom 文件中引入依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
建立實體類和表的關係
引入依賴後,我們需要將實體類和表以及表屬性建立聯繫。我們還是以 Comment 這個類。進行修改。
@Entity
@Table(name = "t_comment")
public class Comment {
@Id //表明映射主鍵id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; //評論id
private String content; //評論內容
private String author; //評論作者
@Column(name = "a_id")
private Integer aId; //外鍵:表示當前這條評論是屬於那篇文章
//getter()/setter()
}
- 首先需要 @Entity 標識這個實體類,可以被處理
- @Table() 註解指定數據庫對應的表名
- @Id 用來指定表的主鍵。
- @GeneratedValue() 用來指定主鍵的類型
- @Column 用來指定這個屬性對應的表的列名,如果類屬性和表列名一致可不指定,不一致就需要指定。
創建一個接口
我們接下來創建一個接口來使用它,繼承JpaRepository 。有兩個參數,第一個參數是是對應的實體類對象,第二個參數主鍵數據類型。
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 都是基於關係型數據庫操作的,我們上面操作的就是mysql 數據庫。現在redis 也經常在項目中使用,那springboot 整合使用redis 也很方便。
引入依賴
一樣的,我們首先需要引入依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置redis 連接信息
在application.propertis 中增加redis 的相關配置
#redis服務器地址
spring.redis.host=127.0.0.1
#redis服務器連接端口
spring.redis.port=6379
#redis服務器連接密碼
spring.redis.password=
其實到現在,我們就已經整合好了,可以在項目中操作redis 數據庫啦。
我們來寫一個測試方法,分別是插入和查找。
@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 。這個就相當於 JdbcTemplate 操作數據庫一樣。兄弟們現在明白了吧,相當於是沒有使用mybatis 或者jpa 這些框架,而是簡單粗暴的操作數據庫了。
現在很多公司使用數據庫也是直接使用 StringRedisTemplate 或者 RedisTemplate 來操作的redis 的數據庫的,因爲基於redis 的持久層框架還不流行。當然我們也可以使用,接下來我們來點騷的。
創建一個實體類。
@RedisHash(value = "persons") //指定實體類對象在redis中的存儲空間
public class Person {
@Id // 用來標識實體類主鍵 字符串形式的hashkey標識唯一的實體類對象id
private String id;
@Indexed // 用來標識對應屬性在redis中生成二級索引
private String firstname;
@Indexed
private String lastname;
private Address address;
}
- @RedisHash 用來指定類的儲存類型,這裏使用的的是RedisHash 表示在數據庫中使用hash 存儲。值得注意的是只有@RedisHash 這個註解來作用於實體類上,這個persons 更像是文件夾,key 的前綴。
- @Id 表明主鍵,其實就是redis 中hash 結構的和前綴組成 key
- @Indexed,用來標識redis 數據庫生成二級索引,方便條件查詢,一樣的和前綴以及屬性名組成key。
創建一個接口。
這裏繼承的是CrudRepository 。並且也是基於jpa 範式的,感興趣的可以試試。
public interface PersonRepository extends CrudRepository<Person, String> {
// 根據城市信息查詢對應的人
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數據庫中添加了數據
personRepository.save(person);
}
@Test
public void selectPerson(){
List<Person> list = personRepository.findByAddress_City("北京");
for (Person person : list) {
System.out.println(person);
}
}
我們在看看redis 數據庫。
我們在來看下。這些key 都是什麼類型存儲的。除了key 爲persons:916b5570-5c7f-4a96-b25f-98c9a2f1f43e 是hash 其他的都是set
說明我們創建的索引,都是使用set 來存儲的,並且這些索引只是存放了一個key 值,也就是我們真正存數據的地方。
而 persons:916b5570-5c7f-4a96-b25f-98c9a2f1f43e:idx 存放的是其他索引的key .
這樣我們也可以通過jpa 這種操作特別是比較負責的對象,我們也能很好的處理啦。
總結
到這就結束啦,知道在springboot 中怎麼是用mybatis,spring data jpa,redis 就可以啦。
記得給我點個贊喔!!!
記得給我點個贊喔!!!
記得給我點個贊喔!!!