最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot實戰(zhàn)記錄之數(shù)據(jù)訪問

 更新時間:2022年04月06日 08:38:27   作者:hjk-airl  
對于數(shù)據(jù)訪問層,無論是SQL還是NOSQL,Spring Boot默認采用整合Spring Data的方式進行統(tǒng)一處理,添加大量自動配置,屏蔽了很多設(shè)置,下面這篇文章主要介紹了SpringBoot實戰(zhàn)記錄之數(shù)據(jù)訪問,需要的朋友可以參考下

前言

在開發(fā)中我們通常會對數(shù)據(jù)庫的數(shù)據(jù)進行操作,SpringBoot對關(guān)系性和非關(guān)系型數(shù)據(jù)庫的訪問操作都提供了非常好的整合支持。SpringData是spring提供的一個用于簡化數(shù)據(jù)庫訪問、支持云服務(wù)的開源框架。它是一個傘狀項目,包含大量關(guān)系型和非關(guān)系型數(shù)據(jù)庫數(shù)據(jù)訪問解決方案,讓我們快速簡單的使用各種數(shù)據(jù)訪問技術(shù),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ù)以及獲取結(jié)果集。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)建表并插入相關(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)建項目并引入相關(guān)啟動器

按照之前的方式創(chuàng)建一個springboot項目,并在pom.xml里導(dǎo)入依賴。我們創(chuàng)建一個名為springboot-01的springboot項目。并且導(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ù)庫,便于我們可視化操作,這個不連接也不會影響我們程序的執(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ù)源需要導(dǎo)入相關(guān)依賴,并且進行配置。springboot2.x版本默認使用的是hikari數(shù)據(jù)源。

## 選著數(shù)據(jù)庫驅(qū)動類型
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();
    }
}

目前整個包結(jié)構(gòu)

注解方式整合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ù)庫的屬性名不太一樣的可能返回結(jié)果可能為空,我們可以開器駝峰命名匹配映射。

在application.properties添加配置。

## 開啟駝峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true

這里使用注解實現(xiàn)了整合mybatis。mybatis雖然在寫一些簡單sql比較方便,但是寫一些復(fù)雜的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文檔中哪復(fù)制模板,然后再寫也可以記錄下來,方便下次寫

<?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寫對應(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>

編寫測試

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)缺點

注解方便,書寫簡單,但是不方便寫復(fù)雜的sql。

xml雖然比較麻煩,但是它的可定制化強,能夠?qū)崿F(xiàn)復(fù)雜的sql語言。

兩者結(jié)合使用會有比較好的結(jié)果。

整合Redis

Redis是一個開源的、內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲系統(tǒng),它可以作用于數(shù)據(jù)庫、緩存、消息中間件,并提供多種語言的API。redis支持多種數(shù)據(jù)結(jié)構(gòu),String、hasher、lists、sets、等。同時內(nèi)置了復(fù)本replication、LUA腳本LUA scripting、LRU驅(qū)動時間LRU eviction、事務(wù)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,也可以手動設(shè)置id。
  • Indexed 用于標識對應(yīng)屬性在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,但是需要導(dǎo)入相關(guān)包。

添加配置文件

在application.properties中添加redis數(shù)據(jù)庫連接配置。

## redis服務(wù)器地址
spring.redis.host=127.0.0.1
## redis服務(wù)器練級端口
spring.redis.port=6379
## redis服務(wù)器密碼默認為空
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);

    }

}

總結(jié)

我們分別對mybatis和redis進行整合。

mybaitis:

注解:導(dǎo)入依賴->創(chuàng)建實體類->屬性配置->編寫配置類->編寫mapper接口->進行測試。

xml:導(dǎo)入依賴->創(chuàng)建實體類->屬性配置(配置數(shù)據(jù)庫等,配置xml路徑)->mapper接口->xml實現(xiàn)->測試

redis:導(dǎo)入依賴->實體類->實現(xiàn)接口->配置redis屬性->測試

到此這篇關(guān)于SpringBoot實戰(zhàn)記錄之數(shù)據(jù)訪問的文章就介紹到這了,更多相關(guān)SpringBoot數(shù)據(jù)訪問內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Springboot整合Druid實現(xiàn)對訪問的監(jiān)控方式

    Springboot整合Druid實現(xiàn)對訪問的監(jiān)控方式

    這篇文章主要介紹了Springboot整合Druid實現(xiàn)對訪問的監(jiān)控方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Spring?cloud負載均衡@LoadBalanced?&?LoadBalancerClient

    Spring?cloud負載均衡@LoadBalanced?&?LoadBalancerClient

    由于Spring?cloud2020之后移除了Ribbon,直接使用Spring?Cloud?LoadBalancer作為客戶端負載均衡組件,我們討論Spring負載均衡以Spring?Cloud2020之后版本為主,學習Spring?Cloud?LoadBalance
    2023-11-11
  • Java向MySQL添加中文數(shù)據(jù)數(shù)據(jù)庫顯示亂碼的解決方案

    Java向MySQL添加中文數(shù)據(jù)數(shù)據(jù)庫顯示亂碼的解決方案

    在用springboot做項目時,由于重新安裝了本地Mysql數(shù)據(jù)庫(5.7版本)在前臺向數(shù)據(jù)庫插入和更新數(shù)據(jù)可的時候,涉及中文的時候在數(shù)據(jù)庫一直顯示異常,所以本文給大家介紹了相關(guān)的解決方案,需要的朋友可以參考下
    2024-02-02
  • SpringBoot攔截器與文件上傳實現(xiàn)方法與源碼分析

    SpringBoot攔截器與文件上傳實現(xiàn)方法與源碼分析

    其實spring boot攔截器的配置方式和springMVC差不多,只有一些小的改變需要注意下就ok了。本文主要給大家介紹了關(guān)于如何在Springboot實現(xiàn)登陸攔截器與文件上傳功能,需要的朋友可以參考下
    2022-10-10
  • java實現(xiàn)微信支付結(jié)果通知

    java實現(xiàn)微信支付結(jié)果通知

    這篇文章主要為大家詳細介紹了java實現(xiàn)微信支付結(jié)果通知,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • 詳解SpringBoot如何自定義注解

    詳解SpringBoot如何自定義注解

    注解,也叫元數(shù)據(jù),一種代碼級別的說明,它是JDK1.5及以后版本引入的一個特性,與類、接口、枚舉是在同一個層次,本文給大家詳細介紹了SpringBoot如何自定義注解,文中通過代碼講解的非常詳細,需要的朋友可以參考下
    2024-08-08
  • Netty搭建WebSocket服務(wù)器實戰(zhàn)教程

    Netty搭建WebSocket服務(wù)器實戰(zhàn)教程

    這篇文章主要介紹了Netty搭建WebSocket服務(wù)器實戰(zhàn),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2024-03-03
  • Java中URL的處理方法詳解

    Java中URL的處理方法詳解

    URL(Uniform?Resource?Locator)中文名為統(tǒng)一資源定位符,有時也被俗稱為網(wǎng)頁地址,表示為互聯(lián)網(wǎng)上的資源,本文主要為大家介紹了Java是如何處理URL的,感興趣的可以了解一下
    2023-05-05
  • Java8 lambda表達式2種常用方法代碼解析

    Java8 lambda表達式2種常用方法代碼解析

    這篇文章主要介紹了Java8 lambda表達式2種常用方法代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-08-08
  • SpringBoot實現(xiàn)本地文件存儲及預(yù)覽過程

    SpringBoot實現(xiàn)本地文件存儲及預(yù)覽過程

    這篇文章主要介紹了SpringBoot實現(xiàn)本地文件存儲及預(yù)覽過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11

最新評論

高州市| 吴川市| 雅江县| 郑州市| 绩溪县| 长治市| 靖江市| 福鼎市| 临泉县| 紫金县| 长顺县| 三原县| 千阳县| 钟山县| 叙永县| 宁国市| 井陉县| 日喀则市| 云和县| 连城县| 阿克苏市| 七台河市| 沧源| 波密县| 台安县| 彝良县| 怀远县| 龙口市| 清原| 广州市| 石景山区| 玉林市| 阿坝| 汶上县| 梁河县| 凤城市| 铜鼓县| 泸州市| 广元市| 中西区| 乌拉特前旗|