3-Spring Boot的数据访问
发布日期:2021-04-30 21:00:47
浏览次数:142
分类:精选文章
本文共 6994 字,大约阅读时间需要 23 分钟。
Spring Boot 数据访问层概述
在开发中,数据操作是核心任务之一。Spring Boot通过简化配置和统一模板,为关系型和非关系型数据库提供了强大的支持。以下将详细介绍Spring Boot如何整合数据库以及相关技术的应用。
常见数据库依赖启动器
Spring Boot 提供了多种数据库依赖启动器,例如MySQL、MongoDB等。通过选择合适的启动器,可以快速实现数据库的连接与操作。这些启动器通常包含了预设的配置和模板,简化了开发流程。
Spring Boot 整合 MyBatis
MyBatis 是一个流行的ORM框架,Spring Boot 提供了对其的优雅集成。以下是整合 MyBatis 的步骤:
1. 数据库准备
- 创建数据库
springbootdata - 创建表
t_article和t_commentCREATE 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;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;
- 插入示例数据:
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');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. 项目创建与依赖
使用Spring Boot Start Project创建项目,选择MySQL和MyBatis依赖。在项目中创建实体类:
public class Comment { private Integer id; private String content; private String author; private Integer aId; // 添加set、get、toString方法}public class Article { private Integer id; private String title; private String content; private List commentList; // 添加set、get、toString方法} 3. 配置文件
在 application.properties 中添加数据库配置:
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=root# 可以不用配置,由druid-spring-boot-starter自动识别数据源spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.initialSize=20spring.datasource.minIdle=10spring.datasource.maxActive=100
在POM文件中添加Druid数据源依赖:
com.alibaba druid-spring-boot-starter 1.1.10
创建自定义配置类:
@Configurationpublic class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource getDruid() { return new DruidDataSource(); }} 4. MyBatis配置
通过注解方式整合MyBatis:
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);} 5. 测试验证
确保数据库连接成功,并验证接口方法:
@Autowiredprivate CommentMapper commentMapper;@Testpublic void selectComment() { Comment comment = commentMapper.findById(1); System.out.println(comment);} 6. 配置文件优化
在全局配置文件中添加MyBatis配置:
mybatis.mapper-locations=classpath:mapper/*.xmlmybatis.type-aliases-package=com.itheima.domain
通过XML映射文件定义查询和更新操作:
UPDATE t_article SET title=#{title}, content=#{content} WHERE id=#{id}
Spring Boot 整合 JPA
Spring Data JPA 提供了对JPA的支持,简化了数据操作。
1. 实体类配置
创建实体类并注解:
@Entity(name = "t_comment")public class Discuss { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "a_id") private Integer aId; private String content; private String author; // 添加get、set方法} 2. Repository接口
创建自定义Repository:
public interface DiscussRepository extends JpaRepository{ List findByAuthorNotNull(); @Query("SELECT c FROM t_comment c WHERE c.aId = ?1") Page getDiscussPaged(Integer aid, Pageable pageable); @Query(value = "SELECT * FROM t_comment WHERE a_Id = ?1", nativeQuery = true) List getDiscussPaged2(Integer aid, Pageable pageable); @Transactional @Modifying @Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2") int updateDiscuss(String author, Integer id); @Transactional @Modifying @Query("DELETE t_comment c WHERE c.id = ?1") int deleteDiscuss(Integer id);}
3. 单元测试
验证Repository方法:
@Autowiredprivate DiscussRepository repository;@Testpublic void selectComment() { Optional optional = repository.findById(1); if (optional.isPresent()) { System.out.println(optional.get()); }}@Testpublic void selectCommentByKeys() { List list = repository.findByAuthorNotNull(); for (Discuss discuss : list) { System.out.println(discuss); }} Spring Boot 整合 Redis
Redis 是一个高性能的键值存储系统,适合缓存和消息中间件。
1. 安装与配置
安装Redis并配置客户端:
- 启动Redis服务
- 打开Redis客户端并配置连接
2. 项目集成
在POM文件中添加Redis依赖:
org.springframework.boot spring-boot-starter-data-redis
创建Redis实体类并注解:
@RedisHash("persons")public class Person { @Id private String id; @Indexed private String firstname; @Indexed private String lastname; private Address address; private List familyList; // 添加get、set方法}@RedisHash("addresses")public class Address { @Indexed private String city; @Indexed private String country; // 添加get、set方法}@RedisHash("families")public class Family { @Indexed private String type; @Indexed private String username; // 添加get、set方法} 创建Repository接口:
public interface PersonRepository extends CrudRepository{ List findByLastname(String lastname); Page findPersonByLastname(String lastname, Pageable pageable); List findByFirstnameAndLastname(String firstname, String lastname); List findByAddressCity(String city); List findByFamilyUsername(String username);}
3. 测试验证
编写单元测试:
@Autowiredprivate PersonRepository repository;@Testpublic void savePerson() { Person person = new Person("张", "有才"); Address address = new Address("北京", "China"); person.setAddress(address); List familyList = new ArrayList<>(); Family dad = new Family("父亲", "张良"); Family mom = new Family("母亲", "李香君"); familyList.add(dad); familyList.add(mom); person.setFamilyList(familyList); Person save = repository.save(person); System.out.println(save); Person save2 = repository.save(new Person("James", "Harden")); System.out.println(save2);} 通过以上步骤,可以实现对数据库、MyBatis、JPA以及Redis的高效集成,简化数据操作流程,提升开发效率。
发表评论
最新留言
感谢大佬
[***.8.128.20]2026年05月31日 20时45分11秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!