SpringBoot實戰(zhàn)記錄之數(shù)據(jù)訪問
前言
在開發(fā)中我們通常會對數(shù)據(jù)庫的數(shù)據(jù)進行操作,SpringBoot對關系性和非關系型數(shù)據(jù)庫的訪問操作都提供了非常好的整合支持。SpringData是spring提供的一個用于簡化數(shù)據(jù)庫訪問、支持云服務的開源框架。它是一個傘狀項目,包含大量關系型和非關系型數(shù)據(jù)庫數(shù)據(jù)訪問解決方案,讓我們快速簡單的使用各種數(shù)據(jù)訪問技術,springboot默認采用整合springdata方式統(tǒng)一的訪問層,通過添加大量的自動配置,引入各種數(shù)據(jù)訪問模板Trmplate以及統(tǒng)一的Repository接口,從而達到簡化數(shù)據(jù)訪問操作。
這里我們分別對MyBatis、Redis進行整合。
SpringBoot整合MyBatis
mybatis作為目前操作數(shù)據(jù)庫的流行框架,spingboot并沒有給出依賴支持,但是mybaitis開發(fā)團隊自己提供了啟動器mybatis-spring-boot-starter依賴。
MyBatis是一款優(yōu)秀的持久層框架,它支持定制sql、存儲過程、高級映射、避免JDBC代碼和手動參數(shù)以及獲取結果集。mybatis不僅支持xml而且支持注解。
環(huán)境搭建
創(chuàng)建數(shù)據(jù)庫
我們創(chuàng)建一個簡單的數(shù)據(jù)庫并插入一些數(shù)據(jù)用于我們下面的操作。
# 創(chuàng)建數(shù)據(jù)庫 CREATE DATABASE studentdata; # 選擇使用數(shù)據(jù)庫 USE studentdata; # 創(chuàng)建表并插入相關數(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)建項目并引入相關啟動器
按照之前的方式創(chuàng)建一個springboot項目,并在pom.xml里導入依賴。我們創(chuàng)建一個名為springboot-01的springboot項目。并且導入阿里的數(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ù)庫,便于我們可視化操作,這個不連接也不會影響我們程序的執(zhí)行,只是方便我們可視化。
創(chuàng)建Student的實體類
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里編寫數(shù)據(jù)庫連接配置。這里我們使用druid數(shù)據(jù)源順便把如何配置數(shù)據(jù)源寫了,用戶名和密碼填寫自己的。使用其他數(shù)據(jù)源需要導入相關依賴,并且進行配置。springboot2.x版本默認使用的是hikari數(shù)據(jù)源。
## 選著數(shù)據(jù)庫驅動類型 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
然后我們編寫一個配置類,把durid數(shù)據(jù)源屬性值注入,并注入到spring容器中
創(chuàng)建一個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 //將該類標記為自定義配置類 public class DataSourceConfig { @Bean //注入一個Datasource對象 @ConfigurationProperties(prefix = "spring.datasource") //注入屬性 public DataSource getDruid(){ return new DruidDataSource(); } }
目前整個包結構
注解方式整合mybatis
創(chuàng)建一個mapper包,并創(chuàng)建一個StudentMapper接口并編寫代碼。mapper其實就和MVC里的dao包差不多。
package com.hjk.mapper; import com.hjk.pojo.Student; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper //這個注解是一個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); }
編寫測試類進行測試
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ù)據(jù)庫的屬性名不太一樣的可能返回結果可能為空,我們可以開器駝峰命名匹配映射。
在application.properties添加配置。
## 開啟駝峰命名匹配映射 mybatis.configuration.map-underscore-to-camel-case=true
這里使用注解實現(xiàn)了整合mybatis。mybatis雖然在寫一些簡單sql比較方便,但是寫一些復雜的sql還是需要xml配置。
使用xml配置Mybatis
我們使用xml要先在application.properties里配置一下,不然springboot識別不了。
## 配置Mybatis的XML配置路徑 mybatis.mapper-locations=classpath:mapper/*.xml ## 配置XML指定實體類別名 mybatis.type-aliases-package=com.hjk.pojo
我們重新書寫StudentMapper類,然后使用xml實現(xiàn)數(shù)據(jù)訪問。這里我們就寫兩個方法,剩下的基本一樣。
package com.hjk.mapper; import com.hjk.pojo.Student; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper //這個注解是一個mybatis接口文件,能被spring掃描到容器中 public interface StudentMapper { public Student getStudentById(Integer id) ; public List<Student> selectAllStudent(); }
我們在resources目錄下創(chuàng)建一個mapper包,并在該包下編寫StudentMapper.xml文件。
我們在寫的時候可以去mybatis文檔中哪復制模板,然后再寫也可以記錄下來,方便下次寫
<?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寫對應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>
編寫測試
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)缺點
注解方便,書寫簡單,但是不方便寫復雜的sql。
xml雖然比較麻煩,但是它的可定制化強,能夠實現(xiàn)復雜的sql語言。
兩者結合使用會有比較好的結果。
整合Redis
Redis是一個開源的、內存中的數(shù)據(jù)結構存儲系統(tǒng),它可以作用于數(shù)據(jù)庫、緩存、消息中間件,并提供多種語言的API。redis支持多種數(shù)據(jù)結構,String、hasher、lists、sets、等。同時內置了復本replication、LUA腳本LUA scripting、LRU驅動時間LRU eviction、事務Transaction和不同級別的磁盤持久化persistence、并且通過Redis Sentinel和自動分區(qū)提供高可用性。
我們添加Redis依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.6.6</version> </dependency>
我們在創(chuàng)建三個實體類用于整合,在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")用于指定操作實體類對象在Redis數(shù)據(jù)庫中的儲存空間,表示Person實體類的數(shù)據(jù)操作都儲存在Redis數(shù)據(jù)庫中名為person的存儲下
- @Id用標識實體類主鍵。在Redis中會默認生成字符串形式的HasHKey表使唯一的實體對象id,也可以手動設置id。
- Indexed 用于標識對應屬性在Redis數(shù)據(jù)庫中的二級索引。索引名稱就是屬性名。
接口整合
編寫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,但是需要導入相關包。
添加配置文件
在application.properties中添加redis數(shù)據(jù)庫連接配置。
## redis服務器地址 spring.redis.host=127.0.0.1 ## redis服務器練級端口 spring.redis.port=6379 ## redis服務器密碼默認為空 spring.redis.password=
測試
編寫測試類,在測試文件下創(chuàng)建一個名為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)建按對象 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ù)庫添加數(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); } }
總結
我們分別對mybatis和redis進行整合。
mybaitis:
注解:導入依賴->創(chuàng)建實體類->屬性配置->編寫配置類->編寫mapper接口->進行測試。
xml:導入依賴->創(chuàng)建實體類->屬性配置(配置數(shù)據(jù)庫等,配置xml路徑)->mapper接口->xml實現(xiàn)->測試
redis:導入依賴->實體類->實現(xiàn)接口->配置redis屬性->測試
到此這篇關于SpringBoot實戰(zhàn)記錄之數(shù)據(jù)訪問的文章就介紹到這了,更多相關SpringBoot數(shù)據(jù)訪問內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- SpringBoot對數(shù)據(jù)訪問層進行單元測試的方法詳解
- 基于Springboot+Mybatis對數(shù)據(jù)訪問層進行單元測試的方式分享
- springboot數(shù)據(jù)訪問和數(shù)據(jù)視圖的使用方式詳解
- 深入了解Springboot核心知識點之數(shù)據(jù)訪問配置
- SpringBoot中Mybatis + Druid 數(shù)據(jù)訪問的詳細過程
- SpringBoot數(shù)據(jù)訪問自定義使用Druid數(shù)據(jù)源的方法
- SpringBoot+MyBatis簡單數(shù)據(jù)訪問應用的實例代碼
- SpringBoot數(shù)據(jù)訪問的實現(xiàn)
相關文章
springboot?max-http-header-size最大長度的那些事及JVM調優(yōu)方式
這篇文章主要介紹了springboot?max-http-header-size最大長度的那些事及JVM調優(yōu)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09BeanUtils.copyProperties()參數(shù)的賦值順序說明
這篇文章主要介紹了BeanUtils.copyProperties()參數(shù)的賦值順序說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09Springboot整合ActiveMQ實現(xiàn)消息隊列的過程淺析
昨天仔細研究了activeMQ消息隊列,也遇到了些坑,下面這篇文章主要給大家介紹了關于SpringBoot整合ActiveMQ的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-02-02Spring?Boot開發(fā)時Java對象和Json對象之間的轉換
在Spring?Boot開發(fā)中,我們經(jīng)常需要處理Java對象和Json對象之間的轉換,本文將介紹如何在Spring?Boot項目中實現(xiàn)Java對象和Json對象之間的轉換,感興趣的朋友跟隨小編一起看看吧2023-09-09