Spring Boot實戰之資料庫操作

来源:https://www.cnblogs.com/paddix/archive/2018/01/03/8178943.html
-Advertisement-
Play Games

上一篇文章通過通過HelloWorld程式講解了Spring boot的基本原理和使用,本文在上篇的基礎上講解Spring boot對資料庫訪問的支持,通過實際的例子演示了Spring boot與JdbcTemplate、JPA以及MyBatis的集成,並對這個過程中遇到的問題進行了分析。 ...


  上篇文章中已經通過一個簡單的HelloWorld程式講解了Spring boot的基本原理和使用。本文主要講解如何通過spring boot來訪問資料庫,本文會演示三種方式來訪問資料庫,第一種是JdbcTemplate,第二種是JPA,第三種是Mybatis。之前已經提到過,本系列會以一個博客系統作為講解的基礎,所以本文會講解文章的存儲和訪問(但不包括文章的詳情),因為最終的實現是通過MyBatis來完成的,所以,對於JdbcTemplate和JPA只做簡單演示,MyBatis部分會完整實現對文章的增刪改查。

一、準備工作

  在演示這幾種方式之前,需要先準備一些東西。第一個就是資料庫,本系統是採用MySQL實現的,我們需要先創建一個tb_article的表:

DROP TABLE IF EXISTS `tb_article`;

CREATE TABLE `tb_article` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL DEFAULT '',
  `summary` varchar(1024) NOT NULL DEFAULT '',
  `status` int(11) NOT NULL DEFAULT '0',
  `type` int(11) NOT NULL,
  `user_id` bigint(20) NOT NULL DEFAULT '0',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `public_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  後續的演示會對這個表進行增刪改查,大家應該會看到這個表裡面並沒有文章的詳情,原因是文章的詳情比較長,如果放在這個表裡面容易影響查詢文章列表的效率,所以文章的詳情會單獨存在另外的表裡面。此外我們需要配置資料庫連接池,這裡我們使用druid連接池,另外配置文件使用yaml配置,即application.yml(你也可以使用application.properties配置文件,沒什麼太大的區別,如果對ymal不熟悉,有興趣也可以查一下,比較簡單)。連接池的配置如下:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/blog?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    driverClassName: com.mysql.jdbc.Driver
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource

  最後,我們還需要建立與資料庫對應的POJO類,代碼如下:

public class Article {
    private Long id;
    private String title;
    private String summary;
    private Date createTime;
    private Date publicTime;
    private Date updateTime;
    private Long userId;
    private Integer status;
private Integer type;

}

  好了,需要準備的工作就這些,現在開始實現資料庫的操作。

 

 二、與JdbcTemplate集成

  首先,我們先通過JdbcTemplate來訪問資料庫,這裡只演示數據的插入,上一篇文章中我們已經提到過,Spring boot提供了許多的starter來支撐不同的功能,要支持JdbcTemplate我們只需要引入下麵的starter就可以了:

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

  現在我們就可以通過JdbcTemplate來實現數據的插入了:

public interface ArticleDao {
    Long insertArticle(Article article);
}

@Repository
public class ArticleDaoJdbcTemplateImpl implements ArticleDao {

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public Long insertArticle(Article article) {
        String sql = "insert into tb_article(title,summary,user_id,create_time,public_time,update_time,status) " +
                "values(:title,:summary,:userId,:createTime,:publicTime,:updateTime,:status)";
        Map<String, Object> param = new HashMap<>();
        param.put("title", article.getTitle());
        param.put("summary", article.getSummary());
        param.put("userId", article.getUserId());
        param.put("status", article.getStatus());
        param.put("createTime", article.getCreateTime());
        param.put("publicTime", article.getPublicTime());
        param.put("updateTime", article.getUpdateTime());
        return (long) jdbcTemplate.update(sql, param);
    }
}

  我們通過JUnit來測試上面的代碼:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class ArticleDaoTest {

    @Autowired
    private ArticleDao articleDao;

    @Test
    public void testInsert() {
        Article article = new Article();
        article.setTitle("測試標題");
        article.setSummary("測試摘要");
        article.setUserId(1L);
        article.setStatus(1);
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setPublicTime(new Date());
        articleDao.insertArticle(article);
    }
}

   要支持上面的測試程式,也需要引入一個starter:

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
 </dependency>

  從上面的代碼可以看出,其實除了引入jdbc的start之外,基本沒有配置,這都是spring boot的自動幫我們完成了配置的過程。上面的代碼需要註意的Application類的位置,該類必須位於Dao類的父級的包中,比如這裡Dao都位於com.pandy.blog.dao這個包下,現在我們把Application.java這個類從com.pandy.blog這個包移動到com.pandy.blog.app這個包中,則會出現如下錯誤:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pandy.blog.dao.ArticleDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
	... 28 more

  也就是說,找不到ArticleDao的實現,這是什麼原因呢?上一篇博文中我們已經看到@SpringBootApplication這個註解繼承了@ComponentScan,其預設情況下只會掃描Application類所在的包及子包。因此,對於上面的錯誤,除了保持Application類在Dao的父包這種方式外,也可以指定掃描的包來解決:

@SpringBootApplication
@ComponentScan({"com.pandy.blog"})
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

    

三、與JPA集成

  現在我們開始講解如何通過JPA的方式來實現資料庫的操作。還是跟JdbcTemplate類似,首先,我們需要引入對應的starter:

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

  然後我們需要對POJO類增加Entity的註解,並指定表名(如果不指定,預設的表名為article),然後需要指定ID的及其生成策略,這些都是JPA的知識,與Spring boot無關,如果不熟悉的話可以看下JPA的知識點:

@Entity(name = "tb_article")
public class Article {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String summary;
    private Date createTime;
    private Date publicTime;
    private Date updateTime;
    private Long userId;
    private Integer status;
}

  最後,我們需要繼承JpaRepository這個類,這裡我們實現了兩個查詢方法,第一個是符合JPA命名規範的查詢,JPA會自動幫我們完成查詢語句的生成,另一種方式是我們自己實現JPQL(JPA支持的一種類SQL的查詢)。

public interface ArticleRepository extends JpaRepository<Article, Long> {

    public List<Article> findByUserId(Long userId);

    @Query("select art from com.pandy.blog.po.Article art where title=:title")
    public List<Article> queryByTitle(@Param("title") String title);
}

  好了,我們可以再測試一下上面的代碼:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class ArticleRepositoryTest {
    @Autowired
    private ArticleRepository articleRepository;

    @Test
    public void testQuery(){
        List<Article> articleList = articleRepository.queryByTitle("測試標題");
        assertTrue(articleList.size()>0);
    }
}

  註意,這裡還是存在跟JdbcTemplate類似的問題,需要將Application這個啟動類未於Respository和Entity類的父級包中,否則會出現如下錯誤:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pandy.blog.dao.ArticleRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
	... 28 more

  當然,同樣也可以通過註解@EnableJpaRepositories指定掃描的JPA的包,但是還是不行,還會出現如下錯誤:

Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.pandy.blog.po.Article
	at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210)
	at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:70)
	at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:68)
	at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:153)
	at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:100)
	at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:82)
	at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199)
	at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
	at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
	at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
	... 39 more

  這個錯誤說明識別不了Entity,所以還需要通過註解@EntityScan來指定Entity的包,最終的配置如下:

@SpringBootApplication
@ComponentScan({"com.pandy.blog"})
@EnableJpaRepositories(basePackages="com.pandy.blog")
@EntityScan("com.pandy.blog")
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

 

四、與MyBatis集成

  最後,我們再看看如何通過MyBatis來實現資料庫的訪問。同樣我們還是要引入starter:

<dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.1.1</version>
</dependency>

  由於該starter不是spring boot官方提供的,所以版本號於Spring boot不一致,需要手動指定。

  MyBatis一般可以通過XML或者註解的方式來指定操作資料庫的SQL,個人比較偏向於XML,所以,本文中也只演示了通過XML的方式來訪問資料庫。首先,我們需要配置mapper的目錄。我們在application.yml中進行配置:

mybatis:
  config-locations: mybatis/mybatis-config.xml
  mapper-locations: mybatis/mapper/*.xml
  type-aliases-package: com.pandy.blog.po

  這裡配置主要包括三個部分,一個是mybatis自身的一些配置,例如基本類型的別名。第二個是指定mapper文件的位置,第三個POJO類的別名。這個配置也可以通過 Java configuration來實現,由於篇幅的問題,我這裡就不詳述了,有興趣的朋友可以自己實現一下。

  配置完後,我們先編寫mapper對應的介面:

public interface ArticleMapper {

    public Long insertArticle(Article article);

    public void updateArticle(Article article);

    public Article queryById(Long id);

    public List<Article> queryArticlesByPage(@Param("article") Article article, @Param("pageSize") int pageSize,
                                             @Param("offset") int offset);

}

  該介面暫時只定義了四個方法,即添加、更新,以及根據ID查詢和分頁查詢。這是一個介面,並且和JPA類似,可以不用實現類。接下來我們編寫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.pandy.blog.dao.ArticleMapper">

    <resultMap id="articleMap" type="com.pandy.blog.po.Article">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="title" property="title" jdbcType="VARCHAR"/>
        <result column="summary" property="summary" jdbcType="VARCHAR"/>
        <result column="user_id" property="userId" jdbcType="INTEGER"/>
        <result column="status" property="status" jdbcType="INTEGER"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
        <result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
        <result column="public_time" property="publicTime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <sql id="base_column">
      title,summary,user_id,status,create_time,update_time,public_time
    </sql>

    <insert id="insertArticle" parameterType="Article">
        INSERT INTO
        tb_article(<include refid="base_column"/>)
        VALUE
        (#{title},#{summary},#{userId},#{status},#{createTime},#{updateTime},#{publicTime})
    </insert>

    <update id="updateArticle" parameterType="Article">
        UPDATE tb_article
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="summary != null">
                summary = #{summary},
            </if>
            <if test="status!=null">
                status = #{status},
            </if>
            <if test="publicTime !=null ">
                public_time = #{publicTime},
            </if>
            <if test="updateTime !=null ">
                update_time = #{updateTime},
            </if>
        </set>
        WHERE id = #{id}
    </update>

    <select id="queryById" parameterType="Long" resultMap="articleMap">
        SELECT id,<include refid="base_column"></include> FROM tb_article
        WHERE id = #{id}
    </select>

    <select id="queryArticlesByPage" resultMap="articleMap">
        SELECT id,<include refid="base_column"></include> FROM tb_article
        <where>
            <if test="article.title != null">
                title like CONCAT('%',${article.title},'%')
            </if>
            <if test="article.userId != null">
                user_id = #{article.userId}
            </if>
        </where>
        limit #{offset},#{pageSize}

    </select>
</mapper>

  最後,我們需要手動指定mapper掃描的包:

@SpringBootApplication
@MapperScan("com.pandy.blog.dao")
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

  好了,與MyBatis的集成也完成了,我們再測試一下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class ArticleMapperTest {

    @Autowired
    private ArticleMapper mapper;

    @Test
    public void testInsert() {
        Article article = new Article();
        article.setTitle("測試標題2");
        article.setSummary("測試摘要2");
        article.setUserId(1L);
        article.setStatus(1);
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setPublicTime(new Date());
        mapper.insertArticle(article);
    }

    @Test
    public void testMybatisQuery() {
        Article article = mapper.queryById(1L);
        assertNotNull(article);
    }

    @Test
    public void testUpdate() {
        Article article = mapper.queryById(1L);
        article.setPublicTime(new Date());
        article.setUpdateTime(new Date());
        article.setStatus(2);
        mapper.updateArticle(article);
    }

    @Test
    public void testQueryByPage(){
        Article article = new Article();
        article.setUserId(1L);
        List<Article> list = mapper.queryArticlesByPage(article,10,0);
        assertTrue(list.size()>0);
    }
}

  

五、總結

    本文演示Spring boot與JdbcTemplate、JPA以及MyBatis的集成,整體上來說配置都比較簡單,以前做過相關配置的同學應該感覺比較明顯,Spring boot確實在這方面給我們提供了很大的幫助。後續的文章中我們只會使用MyBatis這一種方式來進行資料庫的操作,這裡還有一點需要說明一下的是,MyBatis的分頁查詢在這裡是手寫的,這個分頁在正式開發中可以通過插件來完成,不過這個與Spring boot沒什麼關係,所以本文暫時通過這種手動的方式來進行分頁的處理。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ES6提供了新的數據結構Set,它類似於數組,但是成員的值都是唯一的,沒有重覆的值。 Set 本身是一個數據結構,用來生成Set 數據結構。 const s = new Set(); [2,3,5,4,5,2,2,2].forEach(x=>s.add(x)); for(let i of s) { ...
  • 問題1: 範圍(Scope) 思考以下代碼: 控制台會列印出什麼? 答案 上述代碼會列印出5。 (1)在立即執行函數表達式(IIFE)中,有兩個命名,但是其中變數是通過關鍵詞var來聲明的。這就意味著a是這個函數的局部變數。與此相反,b是在全局作用域下的。 (2)在函數中他沒有使用_“嚴格模式”_ ...
  • 錯誤碼: This dependency was not found: * !!vue-style-loader!css-loader?{"minimize":false,"sourceMap":false}!../../node_modules/vue-loader/lib/style-rewri ...
  • 7.1 模塊的概念 把原本實現在一起的功能離散地分散到每個能實現部分功能的塊,這些塊稱為模塊。模塊具有以下幾個好處: 1 程式小,易理解,易調試測試 2 有助於抽象編程設計和複雜程式的封裝 3 內聚性強,耦合性弱 7.2 模塊的引用方法 1.基於ES2015的語法是:import 語句 2 基於Co ...
  • 初看runtime源碼,如入迷宮,小模塊間跳來跳去,我是誰,我在哪,我為什麼要打開它;再看runtime,眉目初現,繪出調用棧,如坐時光機,骨架漸漸明晰。再再看,炳如觀火,代碼層次結構已瞭然於胸。Vue 運行時模塊主要是圍繞 Vue 實例的生命周期展開的,它涵蓋了 Vue 實例生命周期內所需要的全部... ...
  • JQ 實現左右兩側菜單添加、移除 效果圖: JS代碼 html代碼 ...
  • 先不管模式, 把他和他的名字都忘了, 來看看問題 和 設計思路. 為啥要這麼做. 有一家店鋪, 裡面有一個售貨員, 售貨員當然是要賣東西的啦, 客戶進來買完東西, 找售貨員結賬, 那售貨員得知道一共多少錢吧? 一. 初步設計 商品類: 由於價格我使用的是 Long 類型, 所以, 要有一個轉換輸出的 ...
  • 概要 概要 準備工作 檢查數據 處理缺失數據 添加預設值 刪除不完整的行 刪除不完整的列 規範化數據類型 必要的轉換 重命名列名 保存結果 更多資源 準備工作 檢查數據 處理缺失數據 添加預設值 刪除不完整的行 刪除不完整的列 規範化數據類型 必要的轉換 重命名列名 保存結果 更多資源 Pandas ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...