SpringBoot實(shí)戰(zhàn)記錄之?dāng)?shù)據(jù)訪問(wèn)
前言
在開(kāi)發(fā)中我們通常會(huì)對(duì)數(shù)據(jù)庫(kù)的數(shù)據(jù)進(jìn)行操作,SpringBoot對(duì)關(guān)系性和非關(guān)系型數(shù)據(jù)庫(kù)的訪問(wèn)操作都提供了非常好的整合支持。SpringData是spring提供的一個(gè)用于簡(jiǎn)化數(shù)據(jù)庫(kù)訪問(wèn)、支持云服務(wù)的開(kāi)源框架。它是一個(gè)傘狀項(xiàng)目,包含大量關(guān)系型和非關(guān)系型數(shù)據(jù)庫(kù)數(shù)據(jù)訪問(wèn)解決方案,讓我們快速簡(jiǎn)單的使用各種數(shù)據(jù)訪問(wèn)技術(shù),springboot默認(rèn)采用整合springdata方式統(tǒng)一的訪問(wèn)層,通過(guò)添加大量的自動(dòng)配置,引入各種數(shù)據(jù)訪問(wèn)模板Trmplate以及統(tǒng)一的Repository接口,從而達(dá)到簡(jiǎn)化數(shù)據(jù)訪問(wèn)操作。
這里我們分別對(duì)MyBatis、Redis進(jìn)行整合。
SpringBoot整合MyBatis
mybatis作為目前操作數(shù)據(jù)庫(kù)的流行框架,spingboot并沒(méi)有給出依賴支持,但是mybaitis開(kāi)發(fā)團(tuán)隊(duì)自己提供了啟動(dòng)器mybatis-spring-boot-starter依賴。
MyBatis是一款優(yōu)秀的持久層框架,它支持定制sql、存儲(chǔ)過(guò)程、高級(jí)映射、避免JDBC代碼和手動(dòng)參數(shù)以及獲取結(jié)果集。mybatis不僅支持xml而且支持注解。
環(huán)境搭建
創(chuàng)建數(shù)據(jù)庫(kù)
我們創(chuàng)建一個(gè)簡(jiǎn)單的數(shù)據(jù)庫(kù)并插入一些數(shù)據(jù)用于我們下面的操作。
# 創(chuàng)建數(shù)據(jù)庫(kù) CREATE DATABASE studentdata; # 選擇使用數(shù)據(jù)庫(kù) USE studentdata; # 創(chuàng)建表并插入相關(guān)數(shù)據(jù) DROP TABLE IF EXISTS `t_student`; CREATE TABLE `t_student` ( `id` int(20) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` int(8), PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO `t_student` VALUES ('1', 'hjk', '18'); INSERT INTO `t_student` VALUES ('2', '小何', '20');
創(chuàng)建項(xiàng)目并引入相關(guān)啟動(dòng)器
按照之前的方式創(chuàng)建一個(gè)springboot項(xiàng)目,并在pom.xml里導(dǎo)入依賴。我們創(chuàng)建一個(gè)名為springboot-01的springboot項(xiàng)目。并且導(dǎo)入阿里的數(shù)據(jù)源
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.8</version> </dependency>
我們可以在IDEA右邊連接上數(shù)據(jù)庫(kù),便于我們可視化操作,這個(gè)不連接也不會(huì)影響我們程序的執(zhí)行,只是方便我們可視化。
創(chuàng)建Student的實(shí)體類
package com.hjk.pojo; public class Student { private Integer id; private String name; private Integer age; public Student(){ } public Student(String name,Integer age){ this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
在application.properties里編寫(xiě)數(shù)據(jù)庫(kù)連接配置。這里我們使用druid數(shù)據(jù)源順便把如何配置數(shù)據(jù)源寫(xiě)了,用戶名和密碼填寫(xiě)自己的。使用其他數(shù)據(jù)源需要導(dǎo)入相關(guān)依賴,并且進(jìn)行配置。springboot2.x版本默認(rèn)使用的是hikari數(shù)據(jù)源。
## 選著數(shù)據(jù)庫(kù)驅(qū)動(dòng)類型 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/studentdata?serverTimezone=UTC ## 用戶名 spring.datasource.username=root ## 密碼 spring.datasource.password=123456 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource ## 初始化連接數(shù) spring.datasource.druid.initial-size=20 ## 最小空閑數(shù) spring.datasource.druid.min-idle=10 ## 最大連接數(shù) spring.datasource.druid.max-active=100
然后我們編寫(xiě)一個(gè)配置類,把durid數(shù)據(jù)源屬性值注入,并注入到spring容器中
創(chuàng)建一個(gè)config包,并創(chuàng)建名為DataSourceConfig類
package com.hjk.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration //將該類標(biāo)記為自定義配置類 public class DataSourceConfig { @Bean //注入一個(gè)Datasource對(duì)象 @ConfigurationProperties(prefix = "spring.datasource") //注入屬性 public DataSource getDruid(){ return new DruidDataSource(); } }
目前整個(gè)包結(jié)構(gòu)
注解方式整合mybatis
創(chuàng)建一個(gè)mapper包,并創(chuàng)建一個(gè)StudentMapper接口并編寫(xiě)代碼。mapper其實(shí)就和MVC里的dao包差不多。
package com.hjk.mapper; import com.hjk.pojo.Student; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper //這個(gè)注解是一個(gè)mybatis接口文件,能被spring掃描到容器中 public interface StudentMapper { @Select("select * from t_student where id = #{id}") public Student getStudentById(Integer id) ; @Select("select * from t_student") public List<Student> selectAllStudent(); @Insert("insert into t_student values (#{id},#{name},#{age})") public int insertStudent(Student student); @Update("update t_student set name=#{name},age=#{age} where id = #{id}") public int updataStudent(Student student); @Delete("delete from t_student where id=#{id}") public int deleteStudent(Integer id); }
編寫(xiě)測(cè)試類進(jìn)行測(cè)試
package com.hjk; import com.hjk.mapper.StudentMapper; import com.hjk.pojo.Student; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest class Springdata01ApplicationTests { @Autowired private StudentMapper studentMapper; @Test public void selectStudent(){ Student studentById = studentMapper.getStudentById(1); System.out.println(studentById.toString()); } @Test public void insertStudent(){ Student student = new Student("你好",16); int i = studentMapper.insertStudent(student); List<Student> students = studentMapper.selectAllStudent(); for (Student student1 : students) { System.out.println(student1.toString()); } } @Test public void updateStudent(){ Student student = new Student("我叫hjk",20); student.setId(1); int i = studentMapper.updataStudent(student); System.out.println(studentMapper.getStudentById(1).toString()); } @Test public void deleteStudent(){ studentMapper.deleteStudent(1); List<Student> students = studentMapper.selectAllStudent(); for (Student student : students) { System.out.println(student.toString()); } } }
在這里如果你的實(shí)體類的屬性名如果和數(shù)據(jù)庫(kù)的屬性名不太一樣的可能返回結(jié)果可能為空,我們可以開(kāi)器駝峰命名匹配映射。
在application.properties添加配置。
## 開(kāi)啟駝峰命名匹配映射 mybatis.configuration.map-underscore-to-camel-case=true
這里使用注解實(shí)現(xiàn)了整合mybatis。mybatis雖然在寫(xiě)一些簡(jiǎn)單sql比較方便,但是寫(xiě)一些復(fù)雜的sql還是需要xml配置。
使用xml配置Mybatis
我們使用xml要先在application.properties里配置一下,不然springboot識(shí)別不了。
## 配置Mybatis的XML配置路徑 mybatis.mapper-locations=classpath:mapper/*.xml ## 配置XML指定實(shí)體類別名 mybatis.type-aliases-package=com.hjk.pojo
我們重新書(shū)寫(xiě)StudentMapper類,然后使用xml實(shí)現(xiàn)數(shù)據(jù)訪問(wèn)。這里我們就寫(xiě)兩個(gè)方法,剩下的基本一樣。
package com.hjk.mapper; import com.hjk.pojo.Student; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper //這個(gè)注解是一個(gè)mybatis接口文件,能被spring掃描到容器中 public interface StudentMapper { public Student getStudentById(Integer id) ; public List<Student> selectAllStudent(); }
我們?cè)趓esources目錄下創(chuàng)建一個(gè)mapper包,并在該包下編寫(xiě)StudentMapper.xml文件。
我們?cè)趯?xiě)的時(shí)候可以去mybatis文檔中哪復(fù)制模板,然后再寫(xiě)也可以記錄下來(lái),方便下次寫(xiě)
<?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="com.hjk.mapper.StudentMapper"><!--這里namespace寫(xiě)對(duì)應(yīng)mapper的全路徑名--> <select id="getStudentById" resultType="Student"> select * from t_student where id = #{id} </select> <select id="selectAllStudent" resultType="Student"> select * from t_student; </select> </mapper>
編寫(xiě)測(cè)試
package com.hjk; import com.hjk.mapper.StudentMapper; import com.hjk.pojo.Student; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest class Springdata01ApplicationTests { @Autowired private StudentMapper studentMapper; @Test public void selectStudent(){ Student studentById = studentMapper.getStudentById(2); System.out.println(studentById.toString()); } @Test public void selectAllStudent(){ List<Student> students = studentMapper.selectAllStudent(); for (Student student : students) { System.out.println(student.toString()); } } }
注解和xml優(yōu)缺點(diǎn)
注解方便,書(shū)寫(xiě)簡(jiǎn)單,但是不方便寫(xiě)復(fù)雜的sql。
xml雖然比較麻煩,但是它的可定制化強(qiáng),能夠?qū)崿F(xiàn)復(fù)雜的sql語(yǔ)言。
兩者結(jié)合使用會(huì)有比較好的結(jié)果。
整合Redis
Redis是一個(gè)開(kāi)源的、內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲(chǔ)系統(tǒng),它可以作用于數(shù)據(jù)庫(kù)、緩存、消息中間件,并提供多種語(yǔ)言的API。redis支持多種數(shù)據(jù)結(jié)構(gòu),String、hasher、lists、sets、等。同時(shí)內(nèi)置了復(fù)本replication、LUA腳本LUA scripting、LRU驅(qū)動(dòng)時(shí)間LRU eviction、事務(wù)Transaction和不同級(jí)別的磁盤(pán)持久化persistence、并且通過(guò)Redis Sentinel和自動(dòng)分區(qū)提供高可用性。
我們添加Redis依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.6.6</version> </dependency>
我們?cè)趧?chuàng)建三個(gè)實(shí)體類用于整合,在pojo包中。
Family類
package com.hjk.pojo; import org.springframework.data.redis.core.index.Indexed; public class Family { @Indexed private String type; @Indexed private String userName; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { return "Family{" + "type='" + type + '\'' + ", userName='" + userName + '\'' + '}'; } }
Adderss類
package com.hjk.pojo; import org.springframework.data.redis.core.index.Indexed; public class Address { @Indexed private String city; @Indexed private String country; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return "Address{" + "city='" + city + '\'' + ", country='" + country + '\'' + '}'; } }
Person類
package com.hjk.pojo; import org.springframework.data.annotation.Id; import org.springframework.data.redis.core.RedisHash; import org.springframework.data.redis.core.index.Indexed; import java.util.List; @RedisHash("person") public class Person { @Id private String id; @Indexed private String firstName; @Indexed private String lastName; private Address address; private List<Family> familyList; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public List<Family> getFamilyList() { return familyList; } public void setFamilyList(List<Family> familyList) { this.familyList = familyList; } @Override public String toString() { return "Person{" + "id='" + id + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", address=" + address + ", familyList=" + familyList + '}'; } }
- RedisHash("person")用于指定操作實(shí)體類對(duì)象在Redis數(shù)據(jù)庫(kù)中的儲(chǔ)存空間,表示Person實(shí)體類的數(shù)據(jù)操作都儲(chǔ)存在Redis數(shù)據(jù)庫(kù)中名為person的存儲(chǔ)下
- @Id用標(biāo)識(shí)實(shí)體類主鍵。在Redis中會(huì)默認(rèn)生成字符串形式的HasHKey表使唯一的實(shí)體對(duì)象id,也可以手動(dòng)設(shè)置id。
- Indexed 用于標(biāo)識(shí)對(duì)應(yīng)屬性在Redis數(shù)據(jù)庫(kù)中的二級(jí)索引。索引名稱就是屬性名。
接口整合
編寫(xiě)Repository接口,創(chuàng)建repository包并創(chuàng)建PersonRepository類
package com.hjk.repository; import com.hjk.pojo.Person; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface PersonRepository extends CrudRepository<Person,String> { List<Person> findByLastName(String lastName); Page<Person> findPersonByLastName(String lastName, Pageable pageable); List<Person> findByFirstNameAndLastName(String firstName,String lastName); List<Person> findByAddress_City(String city); List<Person> findByFamilyList_UserName(String userName); }
這里接口繼承的使CurdRepository接口,也可以繼承JpaRepository,但是需要導(dǎo)入相關(guān)包。
添加配置文件
在application.properties中添加redis數(shù)據(jù)庫(kù)連接配置。
## redis服務(wù)器地址 spring.redis.host=127.0.0.1 ## redis服務(wù)器練級(jí)端口 spring.redis.port=6379 ## redis服務(wù)器密碼默認(rèn)為空 spring.redis.password=
測(cè)試
編寫(xiě)測(cè)試類,在測(cè)試文件下創(chuàng)建一個(gè)名為RedisTests的類
package com.hjk; import com.hjk.pojo.Address; import com.hjk.pojo.Family; import com.hjk.pojo.Person; import com.hjk.repository.PersonRepository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.ArrayList; import java.util.List; @SpringBootTest public class RedisTests { @Autowired private PersonRepository repository; @Test public void redisPerson(){ //創(chuàng)建按對(duì)象 Person person = new Person(); person.setFirstName("王"); person.setLastName("nihao"); Address address = new Address(); address.setCity("北京"); address.setCountry("china"); person.setAddress(address); ArrayList<Family> list = new ArrayList<>(); Family family = new Family(); family.setType("父親"); family.setUserName("你爸爸"); list.add(family); person.setFamilyList(list); //向redis數(shù)據(jù)庫(kù)添加數(shù)據(jù) Person save = repository.save(person); System.out.println(save); } @Test public void selectPerson(){ List<Person> list = repository.findByAddress_City("北京"); for (Person person : list) { System.out.println(person); } } @Test public void updatePerson(){ Person person = repository.findByFirstNameAndLastName("王", "nihao").get(0); person.setLastName("小明"); Person save = repository.save(person); System.out.println(save); } @Test public void deletePerson(){ Person person = repository.findByFirstNameAndLastName("王", "小明").get(0); repository.delete(person); } }
總結(jié)
我們分別對(duì)mybatis和redis進(jìn)行整合。
mybaitis:
注解:導(dǎo)入依賴->創(chuàng)建實(shí)體類->屬性配置->編寫(xiě)配置類->編寫(xiě)mapper接口->進(jìn)行測(cè)試。
xml:導(dǎo)入依賴->創(chuàng)建實(shí)體類->屬性配置(配置數(shù)據(jù)庫(kù)等,配置xml路徑)->mapper接口->xml實(shí)現(xiàn)->測(cè)試
redis:導(dǎo)入依賴->實(shí)體類->實(shí)現(xiàn)接口->配置redis屬性->測(cè)試
到此這篇關(guān)于SpringBoot實(shí)戰(zhàn)記錄之?dāng)?shù)據(jù)訪問(wèn)的文章就介紹到這了,更多相關(guān)SpringBoot數(shù)據(jù)訪問(wèn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot對(duì)數(shù)據(jù)訪問(wèn)層進(jìn)行單元測(cè)試的方法詳解
- 基于Springboot+Mybatis對(duì)數(shù)據(jù)訪問(wèn)層進(jìn)行單元測(cè)試的方式分享
- springboot數(shù)據(jù)訪問(wèn)和數(shù)據(jù)視圖的使用方式詳解
- 深入了解Springboot核心知識(shí)點(diǎn)之?dāng)?shù)據(jù)訪問(wèn)配置
- SpringBoot中Mybatis + Druid 數(shù)據(jù)訪問(wèn)的詳細(xì)過(guò)程
- SpringBoot數(shù)據(jù)訪問(wèn)自定義使用Druid數(shù)據(jù)源的方法
- SpringBoot+MyBatis簡(jiǎn)單數(shù)據(jù)訪問(wèn)應(yīng)用的實(shí)例代碼
- SpringBoot數(shù)據(jù)訪問(wèn)的實(shí)現(xiàn)
相關(guān)文章
Java線程中的常見(jiàn)方法(start方法和run方法)
這篇文章主要介紹了Java線程中的常見(jiàn)方法(start方法和run方法),文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07springboot?max-http-header-size最大長(zhǎng)度的那些事及JVM調(diào)優(yōu)方式
這篇文章主要介紹了springboot?max-http-header-size最大長(zhǎng)度的那些事及JVM調(diào)優(yōu)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09Java詳解實(shí)現(xiàn)ATM機(jī)模擬系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了如何利用Java語(yǔ)言實(shí)現(xiàn)控制臺(tái)版本的ATM銀行管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06BeanUtils.copyProperties()參數(shù)的賦值順序說(shuō)明
這篇文章主要介紹了BeanUtils.copyProperties()參數(shù)的賦值順序說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09Springboot整合ActiveMQ實(shí)現(xiàn)消息隊(duì)列的過(guò)程淺析
昨天仔細(xì)研究了activeMQ消息隊(duì)列,也遇到了些坑,下面這篇文章主要給大家介紹了關(guān)于SpringBoot整合ActiveMQ的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02Spring?Boot開(kāi)發(fā)時(shí)Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換
在Spring?Boot開(kāi)發(fā)中,我們經(jīng)常需要處理Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換,本文將介紹如何在Spring?Boot項(xiàng)目中實(shí)現(xiàn)Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換,感興趣的朋友跟隨小編一起看看吧2023-09-09