实验三 Spring Boot数据访问
一、实验目的
1、掌握Spring Boot整合MyBatis的使用
2、掌握Spring Boot整合JPA的使用
3、掌握Spring Boot整合Redis的使用
二、实验内容
1、使用注解的方式整合MyBatis
2、使用配置文件的方式整合MyBatis
3、使用Spring Boot整合JPA
4、使用Spring Boot整合Redis
三、实验步骤
1、数据准备
①创建数据库
CREATE DATABASE springbootdata;
②创建数据表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;
③ 向数据表t_article插入相关数据
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
④ 创建数据表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;
⑤ 向数据表t_comment插入相关数据
INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '狂奔的蜗牛', '1');
INSERT INTO `t_comment` VALUES ('2', '赞一个', 'tom', '1');
INSERT INTO `t_comment` VALUES ('3', '很详细', 'kitty', '1');
INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '张三', '1');
INSERT INTO `t_comment` VALUES ('5', '很不错', '张杨', '2');
2、创建项目
①创建项目,引入MySQL和MyBatis的依赖启动器
②编写实体类Comment
在src\main\java文件夹下的com.lg.ch03下创建domain文件夹,并在新建的文件夹下创建Comment.java
public class Comment {
private Integer id;
private String content;
private String author;
private Integer aId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getaId() {
return aId;
}
public void setaId(Integer aId) {
this.aId = aId;
}
@Override
public String toString() {
return "Comment{" +
"id=" + id +
", content='" + content + '\'' +
", author='" + author + '\'' +
", aId=" + aId +
'}';
}
}
③编写实体类Article
在domain中创建Article.java
import java.util.List;
public class Article {
private Integer id;
private String title;
private String content;
private List<Comment> commentList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
", commentList=" + commentList +
'}';
}
}
3、依赖添加及配置
① 在resources下的application.properties全局配置文件中进行数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=1234
② 在pom.xml设置数据源类型配置(以阿里巴巴的Druid数据源为例)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
③在resources下的application.properties全局配置文件中设置属性
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=100
mybatis.configuration.map-underscore-to-camel-case=true
4、功能实现
(1)使用注解方式整合MyBatis
① 在com.lg.ch03文件夹下创建mapper文件夹并创建Mapper接口文件CommentMapper.java
import com.lg.domain.Comment;
import org.apache.ibatis.annotations.*;
@Mapper
public interface CommentMapper {
//查询数据操作
@Select("SELECT * FROM t_comment WHERE id =#{id}")
public Comment findById(Integer id);
//插入数据操作
@Insert("INSERT INTO t_comment(content,author,a_id) " + "values (#{content},#{author},#{aId})")
public int insertComment(Comment comment);
//更新数据操作
@Update("UPDATE t_comment SET content=#{content} WHERE id=#{id}")
public int updateComment(Comment comment);
//删除数据操作
@Delete("DELETE FROM t_comment WHERE id=#{id}")
public int deleteComment(Integer id);
}
② 编写测试方法进行接口方法测试以及整合测试
在src\test\java\com.lg.ch03文件夹下的Ch03ApplicationTests中填写
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter03ApplicationTests {
@Autowired
private CommentMapper commentMapper;
@Test
public void selectComment() {
Comment comment = commentMapper.findById(1);
System.out.println(comment);
}
}
③ 程序运行
(2)使用配置文件方式整合 MyBatis
① 在mapper文件夹下创建Mapper接口文件ArticleMapper.java
import com.lg.ch03.domain.Article;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ArticleMapper {
public Article selectArticle(Integer id);
public int updateArticle(Article article);
}
② 在resources下创建mapper文件夹并在其内创建XML映射文件ArticleMapper.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="com.lg.ch03.mapper.ArticleMapper">
<!-- 查询操作:-->
<select id="selectArticle" resultMap="articleWithComment">
SELECT a.*,c.id c_id,c.content c_content,c.author
FROM t_article a,t_comment c
WHERE a.id=c.a_id AND a.id = #{id}
</select>
<!-- 更新操作:-->
<update id="updateArticle" parameterType="Article" >
UPDATE t_article
<set>
<if test="title !=null and title !=''">
title=#{title},
</if>
<if test="content !=null and content !=''">
content=#{content}
</if>
</set>
WHERE id=#{id}
</update>
<!-- 结果集:-->
<resultMap id="articleWithComment" type="Article">
<id property="id" column="id" />
<result property="title" column="title" />
<result property="content" column="content" />
<collection property="commentList" ofType="Comment">
<id property="id" column="c_id" />
<result property="content" column="c_content" />
<result property="author" column="author" />
</collection>
</resultMap>
</mapper>
③ 在resources下的全局配置文件application.properties 文件中配置XML映射文件路径
#配置MyBatis的xml配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置XML映射文件中指定的实体类别名路径
mybatis.type-aliases-package=com.lg.ch03.domain
④ 在Ch03ApplicationTests文件中编写单元测试对接口进行测试
@Autowired
private ArticleMapper articleMapper;
@Test
public void selectArticle() {
Article article = articleMapper.selectArticle(1);
System.out.println(article);
}
⑤ 程序运行
5.使用Spring Boot 整合 JPA
① 在pom文件中添加Spring Data JPA依赖启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
② 编写ORM实体类
在domain文件夹下创建Discuss.java文件
import javax.persistence.*;
@Entity(name = "t_comment")
public class Discuss {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String content;
private String author;
@Column(name = "a_id")
private Integer aId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getaId() {
return aId;
}
public void setaId(Integer aId) {
this.aId = aId;
}
@Override
public String toString() {
return "Discuss{" +
"id=" + id +
", content='" + content + '\'' +
", author='" + author + '\'' +
", aId=" + aId +
'}';
}
}
③ 编写Repository接口
在com.lg.ch03文件夹下创建repository文件夹并在内创建DiscussRepository.java接口文件
import com.lg.ch03.domain.Discuss;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface DiscussRepository extends JpaRepository<Discuss,Integer> {
//查询author非空的Discuss评论集合
public List<Discuss> findByAuthorNotNull();
//根据文章id分页查询Discuss评论集合
@Query("SELECT c FROM t_comment c WHERE c.aId = ?1")
public List<Discuss> getDiscussPaged(Integer aid, Pageable pageable);
//使用元素SQL语句,根据文章id分页查询Discuss评论集合
@Query(value = "SELECT * FROM t_comment WHERE a_Id = ?1",nativeQuery = true)
public List<Discuss> getDiscussPaged2(Integer aid,Pageable pageable);
//根据评论id修改评论作者author
@Transactional
@Modifying
@Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")
public int updateDiscuss(String author,Integer id);
//根据评论id删除评论
@Transactional
@Modifying
@Query("DELETE t_comment c WHERE c.id = ?1")
public int deleteDiscuss(Integer id);
}
④ 编写测试方法
在test\java\com.lg.ch03中创建JpaTests.java添加单元测试
import com.lg.ch03.domain.Discuss;
import com.lg.ch03.repository.DiscussRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Optional;
import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;
@RunWith(SpringRunner.class)
@SpringBootTest
public class JpaTests {
@Autowired
private DiscussRepository repository;
// 1、使用JpaRepository内部方法进行数据操作
@Test
public void selectComment() {
Optional<Discuss> optional = repository.findById(1);
if(optional.isPresent()){
System.out.println(optional.get());
}
System.out.println();
}
// 2、使用方法名关键字进行数据操作
@Test
public void selectCommentByKeys() {
List<Discuss> list = repository.findByAuthorNotNull();
System.out.println(list);
}
// 3、使用@Query注解进行数据操作
@Test
public void selectCommentPaged() {
Pageable pageable = PageRequest.of(0,3);
List<Discuss> allPaged = repository.getDiscussPaged(1, pageable);
System.out.println(allPaged);
}
// 4、使用Example封装参数进行数据查询操作
@Test
public void selectCommentByExample() {
Discuss discuss =new Discuss();
discuss.setAuthor("张三");
Example<Discuss> example = Example.of(discuss);
List<Discuss> list = repository.findAll(example);
System.out.println(list);
}
@Test
public void selectCommentByExampleMatcher() {
Discuss discuss =new Discuss();
discuss.setAuthor("张");
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("author",startsWith());
Example<Discuss> example = Example.of(discuss, matcher);
List<Discuss> list = repository.findAll(example);
System.out.println(list);
}
}
⑤ 整合测试
6.使用Spring Boot 整合 Redis
(1) 在pom文件中添加Spring Data Redis依赖启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
(2)编写实体类
在domain文件下编写实体类
① Family类
import org.springframework.data.redis.core.index.Indexed;
public class Family {
@Indexed
private String type;
@Indexed
private String username;
public Family() {
}
public Family(String type, String username) {
this.type = type;
this.username = 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 + '\'' +
'}';
}
}
② Address类
import org.springframework.data.redis.core.index.Indexed;
public class Address {
@Indexed
private String city;
@Indexed
private String country;
public Address() {
}
public Address(String city, String country) {
this.city = city;
this.country = 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类
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("persons")
public class Person {
@Id
private String id;
@Indexed
private String firstname;
@Indexed
private String lastname;
private Address address;
private List<Family> familyList;
public Person() {
}
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
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 +
'}';
}
}
(3)在repository文件夹下编写接口PersonRepository
import com.lg.ch03.domain.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 page);
List<Person> findByFirstnameAndLastname(String firstname, String lastname);
List<Person> findByAddress_City(String city);
List<Person> findByFamilyList_Username(String username);
}
(4)在application.properties全局配置文件中配置Redis数据库连接
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
(5)编写测试方法
在test\java\com.lg.ch03中创建RedisTests.java添加单元测试
import com.lg.ch03.domain.Address;
import com.lg.ch03.domain.Family;
import com.lg.ch03.domain.Person;
import com.lg.ch03.repository.PersonRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTests {
@Autowired
private PersonRepository repository;
@Test
public void savePerson() {
Person person =new Person("张","有才");
Person person2 =new Person("James","Harden");
// 创建并添加住址信息
Address address=new Address("北京","China");
person.setAddress(address);
// 创建并添加家庭成员
List<Family> list =new ArrayList<>();
Family dad =new Family("父亲","张良");
Family mom =new Family("母亲","李香君");
list.add(dad);
list.add(mom);
person.setFamilyList(list);
// 向Redis数据库添加数据
Person save = repository.save(person);
Person save2 = repository.save(person2);
System.out.println(save);
System.out.println(save2);
}
@Test
public void selectPerson() {
List<Person> list = repository.findByAddress_City("北京");
System.out.println(list);
}
@Test
public void updatePerson() {
Person person = repository.findByFirstnameAndLastname("张","有才").get(0);//取结果的第一个元素
person.setLastname("小明");
Person update = repository.save(person);
System.out.println(update);
}
@Test
public void deletePerson() {
Person person = repository.findByFirstnameAndLastname("张","小明").get(0);
repository.delete(person);
}
}
(6)整合测试