亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 開發 > Java > 正文

Spring Boot實戰之數據庫操作的示例代碼

2024-07-13 10:15:57
字體:
來源:轉載
供稿:網友

上篇文章中已經通過一個簡單的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);}@Repositorypublic 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  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">      </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沒什么關系,所以本文暫時通過這種手動的方式來進行分頁的處理。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
午夜免费在线观看精品视频| 欧美性xxxxxx| 国产精品www网站| 亚洲激情视频在线观看| 精品成人乱色一区二区| 日韩精品中文字幕在线播放| 日本91av在线播放| 91丨九色丨国产在线| 国语自产精品视频在线看| 精品国产电影一区| 欧美一区二粉嫩精品国产一线天| 欧美日韩亚洲视频一区| 成人免费视频在线观看超级碰| 国产福利视频一区二区| 亚洲人成在线观看网站高清| 欧美与黑人午夜性猛交久久久| 亚洲国产日韩欧美在线动漫| 亚洲第一色在线| 97**国产露脸精品国产| 国产精品三级在线| 孩xxxx性bbbb欧美| 日韩中文在线中文网在线观看| 亚洲欧洲国产一区| 日韩av免费一区| 日韩av一区在线观看| 欧美黑人xxx| 97婷婷大伊香蕉精品视频| 欧美超级乱淫片喷水| 欧美激情在线视频二区| 久久视频免费在线播放| 在线播放精品一区二区三区| 久久久久久久久91| 国产主播在线一区| 欧美成人精品在线| 91sa在线看| 91精品在线观| 亚洲va欧美va在线观看| 欧美大片在线免费观看| 欧美激情视频在线| 尤物精品国产第一福利三区| 欧美成人小视频| 在线观看亚洲视频| 97免费在线视频| 清纯唯美亚洲综合| 成人做爽爽免费视频| 国产午夜精品视频免费不卡69堂| 日韩中文在线观看| 8050国产精品久久久久久| 欧亚精品在线观看| 亚洲天堂网在线观看| 久久综合久久八八| 51久久精品夜色国产麻豆| 色www亚洲国产张柏芝| 日韩美女av在线免费观看| 日韩av中文字幕在线免费观看| 久久资源免费视频| 91日本视频在线| 精品久久国产精品| 久久久视频在线| 日韩电影在线观看中文字幕| 91av视频在线观看| 成人av番号网| 色青青草原桃花久久综合| 欧美乱大交做爰xxxⅹ性3| 国产亚洲精品va在线观看| 在线a欧美视频| 91精品国产91久久久久久不卡| 亚洲最新av在线网站| 中文字幕av一区中文字幕天堂| 福利精品视频在线| 亚洲欧美中文在线视频| 成人激情在线观看| 日韩欧美aaa| 亚洲精品wwww| 久久久999国产精品| 日韩av手机在线| 亚洲日本中文字幕免费在线不卡| 色综合老司机第九色激情| 久久99久久亚洲国产| 亚洲欧美日韩精品久久亚洲区| 最新91在线视频| 亚洲精品久久在线| 国产成人小视频在线观看| 国模gogo一区二区大胆私拍| 成人免费淫片视频软件| 欧美成人久久久| 欧美性生交xxxxx久久久| 亚洲综合视频1区| 亚洲美女精品久久| 欧美激情在线观看| 久久免费视频网站| 欧美日韩国产专区| 久久久亚洲欧洲日产国码aⅴ| 日韩电影第一页| 国内精品免费午夜毛片| 亚洲高清福利视频| 国产午夜一区二区| 国产精品久久久久久av下载红粉| 亚洲三级免费看| 国产成人精品亚洲精品| 亚洲欧美日韩另类| 国产一区二区三区久久精品| 亚洲综合第一页| 久久久久久九九九| 一区二区福利视频| 日本久久久a级免费| 91精品久久久久久久久青青| 中文字幕亚洲天堂| 欧美高清videos高潮hd| 久久久久久国产精品三级玉女聊斋| 亚洲精品一区在线观看香蕉| 色妞在线综合亚洲欧美| 久精品免费视频| 亚洲电影天堂av| 亚洲激情在线观看视频免费| 日韩中文字幕在线观看| 岛国av一区二区在线在线观看| xxxx性欧美| 国产亚洲xxx| 国产精品一二三视频| 亚洲美女性视频| 亚洲成人在线网| 亚洲国产一区自拍| 欧美巨猛xxxx猛交黑人97人| www.日本久久久久com.| 国产亚洲欧美一区| 日韩av免费在线| 欧美激情喷水视频| 国产成人精品免高潮在线观看| 另类视频在线观看| 91免费福利视频| 91情侣偷在线精品国产| 欧美一区二区三区……| 欧美做受高潮电影o| 久久激情视频久久| 国语自产精品视频在线看一大j8| 日韩不卡中文字幕| 中文字幕国产精品久久| 亚洲精品福利资源站| 欧美久久精品一级黑人c片| 久久精品视频在线观看| 久久最新资源网| 日韩中文在线中文网三级| 国产精品激情av电影在线观看| 欧美裸体xxxx极品少妇| 日韩在线视频二区| 欧美日韩在线视频一区二区| 国产精品久久久久久超碰| 97香蕉久久夜色精品国产| 琪琪亚洲精品午夜在线| 欧美激情视频网| 久久成人人人人精品欧| 成人有码在线视频| 欧美精品成人91久久久久久久| 在线午夜精品自拍| 日韩高清电影免费观看完整版| 日韩电影大全免费观看2023年上| 国产视频欧美视频| 日韩男女性生活视频| 国产91在线播放九色快色| 国内成人精品一区| 亚洲精品99999| 国产精品一区二区三区在线播放| 国内精品久久影院|