SpringBoot实战记录之数据访问

网友投稿 277 2022-08-16


SpringBoot实战记录之数据访问

目录前言SpringBoot整合MyBatis环境搭建注解方式整合mybatis使用xml配置Mybatis整合Redis接口整合测试总结

前言

在开发中我们通常会对数据库的数据进行操作,SpringBoot对关系性和非关系型数据库的访问操作都提供了非常好的整合支持。SpringData是spring提供的一个用于简化数据库访问、支持云服务的开源框架。它是一个伞状项目,包含大量关系型和非关系型数据库数据访问解决方案,让我们快速简单的使用各种数据访问技术,springboot默认采用整合springdata方式统一的访问层,通过添加大量的自动配置,引入各种数据访问模板Trmplate以及统一的Repository接口,从而达到简化数据访问操作。

这里我们分别对MyBatis、Redis进行整合。

SpringBoot整合MyBatis

mybatis作为目前操作数据库的流行框架,spingboot并没有给出依赖支持,但是mybaitis开发团队自己提供了启动器mybatis-spring-boot-starter依赖。MyBatis是一款优秀的持久层框架,它支持定制sql、存储过程、高级映射、避免JDBC代码和手动参数以及获取结果集。mybatis不仅支持xml而且支持注解。

环境搭建

创建数据库

我们创建一个简单的数据库并插入一些数据用于我们下面的操作。

# 创建数据库

CREATE DATABASE studentdata;

# 选择使用数据库

USE studentdata;

# 创建表并插入相关数据

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');

创建项目并引入相关启动器

按照之前的方式创建一个springboot项目,并在pom.xml里导入依赖。我们创建一个名为springboot-01的springboot项目。并且导入阿里的数据源

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.2.2

mysql

mysql-connector-java

8.0.28

com.alibaba

druid-spring-boot-starter

1.2.8

我们可以在IDEA右边连接上数据库,便于我们可视化操作,这个不连接也不会影响我们程序的执行,只是方便我们可视化。

创建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里编写数据库连接配置。这里我们使用druid数据源顺便把如何配置数据源写了,用户名和密码填写自己的。使用其他数据源需要导入相关依赖,并且进行配置。springboot2.x版本默认使用的是hikari数据源。

## 选着数据库驱动类型

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

## 初始化连接数

spring.datasource.druid.initial-size=20

## 最小空闲数

spring.datasource.druid.min-idle=10

## 最大连接数

spring.datasource.druid.max-active=100

然后我们编写一个配置类,把durid数据源属性值注入,并注入到spring容器中

创建一个config包,并创建名为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

创建一个mapper包,并创建一个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 LEygQXQGist 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 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 students = studentMapper.selectAllStudent();

for (Student student : students) {

System.out.println(student.toString());

}

}

}

在这里如果你的实体类的属性名如果和数据库的属性名不太一样的可能返回结果可能为空,我们可以开器驼峰命名匹配映射。

在application.properties添加配置。

## 开启驼峰命名匹配映射

mybatis.configuration.map-underscore-to-camel-case=true

这里使用注解实现了整合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实现数据访问。这里我们就写两个方法,剩下的基本一样。

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 selectAllStudent();

}

我们在resources目录下创建一个mapper包,并在该包下编写StudentMapper.xml文件。

我们在写的时候可以去mybatis文档中哪复制模板,然后再写也可以记录下来,方便下次写

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select * from t_student where id = #{id}

select * from t_student;

编写测试

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 students = studentMapper.selectAllStudent();

for (Student student : students) {

System.out.println(student.toString());

}

}

}

注解和xml优缺点

注解方便,书写简单,但是不方便写复杂的sql。

xml虽然比较麻烦,但是它的可定制化强,能够实现复杂的sql语言。

两者结合使用会有比较好的结果。

整合Redis

Redis是一个开源的、内存中的数据结构存储系统,它可以作用于数据库、缓存、消息中间件,并提供多种语言的API。redis支持多种数据结构,String、hasher、lists、sets、等。同时内置了复本replication、LUA脚本LUA scripting、LRU驱动时间LRU eviction、事务Transaction和不同级别的磁盘持久化persistence、并且通过Redis Sentinel和自动分区提供高可用性。

我们添加Redis依赖。

org.springframework.boot

spring-boot-starter-data-redis

2.6.6

我们在创建三个实体类用于整合,在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 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 getFamilyList() {

return familyList;

}

public void setFamilyList(List familyList) {

this.familyList = familyList;

}

@Override

public String toString() {

return "Person{" +

"id='" + id + '\'' +

", firstName='" + firstName + '\'' +

", lastName='" + lastName + '\'' +

", address=" + address +

", familyList=" + familyList +

'}';

}

}

RedisHash("person")用于指定操作实体类对象在Redis数据库中的储存空间,表示Person实体类的数据操作都储存在Redis数据库中名为person的存储下@Id用标识实体类主键。在Redis中会默认生成字符串形式的HasHKey表使唯一的实体对象id,也可以手动设置id。Indexed 用于标识对应属性在Redis数据库中的二级索引。索引名称就是属性名。

接口整合

编写Repository接口,创建repository包并创建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 {

List findByLastName(String lastName);

Page findPersonByLastName(String lastName, Pageable pageable);

List findByFirstNameAndLastName(String firstName,String lastName);

List findByAddress_City(String city);

List findByFamilyList_UserName(String userName);

}

这里接口继承的使CurdRepository接口,也可以继承JpaRepository,但是需要导入相关包。

添加配置文件

在application.properties中添加redis数据库连接配置。

## redis服务器地址

spring.redis.host=127.0.0.1

## redis服务器练级端口

spring.redis.port=6379

## redis服务器密码默认为空

spring.redis.password=

测试

编写测试类,在测试文件下创建一个名为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(){

//创建按对象

Person person = new Person();

person.setFirstName("王");

person.setLastName("nihao");

Address address = new Address();

address.setCity("北京");

address.setCountry("china");

person.setAddress(address);

ArrayList list = new ArrayList<>();

Family family = new Family();

family.setType("父亲");

family.setUserName("你爸爸");

list.add(family);

person.setFamilyList(list);

//向redis数据库添加数据

Person save = repository.save(person);

System.out.println(save);

}

@Test

public void selectPerson(){

List 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:

注解:导入依赖->创建实体类->属性配置->编写配置类->编写mapper接口->进行测试。

xml:导入依赖->创建实体类->属性配置(配置数据库等,配置xml路径)->mapper接口->xml实现->测试

redis:导入依赖->实体类->实现接口->配置redis属性->测试


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Mybatis分页的4种方式实例
下一篇:Java实现无向图的示例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~