欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot实战之数据库操作的示例代码

程序员文章站 2023-12-19 19:50:34
上篇文章中已经通过一个简单的helloworld程序讲解了spring boot的基本原理和使用。本文主要讲解如何通过spring boot来访问数据库,本文会演示三种方式...

上篇文章中已经通过一个简单的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没什么关系,所以本文暂时通过这种手动的方式来进行分页的处理。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: