Spring Boot实战:数据库操作

From: https://www.cnblogs.com/paddix/p/8178943.html

  上篇文章中已经通过一个简单的HelloWorld程序讲解了Spring boot的基本原理和使用。本文主要讲解如何通过spring boot来访问数据库,本文会演示三种方式来访问数据库,第一种是JdbcTemplate,第二种是JPA,第三种是Mybatis。之前已经提到过,本系列会以一个博客系统作为讲解的基础,所以本文会讲解文章的存储和访问(但不包括文章的详情),因为最终的实现是通过MyBatis来完成的,所以,对于JdbcTemplate和JPA只做简单演示,MyBatis部分会完整实现对文章的增删改查。

一、准备工作

  在演示这几种方式之前,需要先准备一些东西。第一个就是数据库,本系统是采用MySQL实现的,我们需要先创建一个tb_article的表:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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不熟悉,有兴趣也可以查一下,比较简单)。连接池的配置如下:

1

2

3

4

5

6

7

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类,代码如下:

1

2

3

4

5

6

7

8

9

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;<br>    private Integer type;<br><br>}

  好了,需要准备的工作就这些,现在开始实现数据库的操作。

 

 二、与JdbcTemplate集成

  首先,我们先通过JdbcTemplate来访问数据库,这里只演示数据的插入,上一篇文章中我们已经提到过,Spring boot提供了许多的starter来支撑不同的功能,要支持JdbcTemplate我们只需要引入下面的starter就可以了:

1

2

3

4

<dependency>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-jdbc</artifactId>

</dependency>

  现在我们就可以通过JdbcTemplate来实现数据的插入了:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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来测试上面的代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

@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:

1

2

3

4

5

<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这个包中,则会出现如下错误:

1

2

3

4

5

6

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的父包这种方式外,也可以指定扫描的包来解决:

1

2

3

4

5

6

7

@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:

1

2

3

4

<dependency>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

  然后我们需要对POJO类增加Entity的注解,并指定表名(如果不指定,默认的表名为article),然后需要指定ID的及其生成策略,这些都是JPA的知识,与Spring boot无关,如果不熟悉的话可以看下JPA的知识点:

1

2

3

4

5

6

7

8

9

10

11

12

13

@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的查询)。

1

2

3

4

5

6

7

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);

}

  好了,我们可以再测试一下上面的代码:

1

2

3

4

5

6

7

8

9

10

11

12

@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类的父级包中,否则会出现如下错误:

1

2

3

4

5

6

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的包,但是还是不行,还会出现如下错误:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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的包,最终的配置如下:

1

2

3

4

5

6

7

8

9

@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:

1

2

3

4

5

<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中进行配置:

1

2

3

4

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对应的接口:

1

2

3

4

5

6

7

8

9

10

11

12

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文件:

+ View Code

  最后,我们需要手动指定mapper扫描的包:

1

2

3

4

5

6

7

@SpringBootApplication

@MapperScan("com.pandy.blog.dao")

public class Application {

    public static void main(String[] args) throws Exception {

        SpringApplication.run(Application.class, args);

    }

}

  好了,与MyBatis的集成也完成了,我们再测试一下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

@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没什么关系,所以本文暂时通过这种手动的方式来进行分页的处理。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/402656.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PDB调试Python程序

pdb是python内置的调试工具, 它可以在终端中调试Python程序, 这允许pdb在很多无法安装IDE的服务器上使用. 虽然远程调试使用广泛, 但在必要的时候&#xff08;比如难以在本地搭建运行环境&#xff09;pdb仍然是一个便利的选择. 我们可以在python源代码中设置断点&#xff1a; i…

不使用中间变量交换2个数据

2019独角兽企业重金招聘Python工程师标准>>> 第一种方法&#xff1a; <!-- lang: cpp -->aab;ba-b;aa-b;可能产生越界和溢出。 第二种方法&#xff1a; <!-- lang: cpp -->aa^b;ba^b;aa^b;这种方法只适用整形数。 写成宏的形式 <!-- lang: cpp -->…

slf4j的简单用法以及与log4j的区别

From: https://www.cnblogs.com/qlqwjy/p/9275415.html 之前在项目中用的日志记录器都是log4j的日志记录器&#xff0c;可是到了新公司发现都是slf4j&#xff0c;于是想着研究一下slf4j的用法。 注意:每次引入Logger的时候注意引入的jar包&#xff0c;因为有Logger的包太多了。…

PS不能存储,因为程序错误

当PS中遇到不能存储文件&#xff0c;因为程序错误时&#xff0c;可以这样&#xff1a; http://www.zcool.com.cn/article/ZMTgwOTQw.html 转载于:https://www.cnblogs.com/kjcy8/p/6072599.html

MEF相关总结

&#xff08;1&#xff09;蛮好的一篇文章&#xff1a;LoveJenny的MEF 打造的插件系统 一个简单单很能容易理解的例子讲解了MEF. &#xff08;2&#xff09;原理方面的看Bēniaǒ成长笔记的《MEF程序设计指南》博文汇总 &#xff08;3&#xff09;http://www.cnblogs.com/pszw/…

JdbcType类型和Java类型的对应关系

From: https://www.cnblogs.com/tongxuping/p/7134113.html 在Oracle中有些字段不是必填时在用户使用的时候会出现数据null的情况。这个时候在Oracle中是无法进行插入的。 1 JDBC Type Java Type 2 CHAR String 3 VARCHAR String 4 L…

MyBatis Generator配置文件翻译

From: https://www.cnblogs.com/GaiDynasty/p/4088531.html <classPathEntry> 驱动文件指定配置项 <classPathEntry location"/Program Files/IBM/SQLLIB/java/db2java.zip" /> <columnOverride> 将数据库中的字段重命名为实体类的属性 colu…

java实现计算字符串表达式

ScriptEngineManager manager new ScriptEngineManager(); ScriptEngine engine manager.getEngineByName("JavaScript");Object result engine.eval("12");转载于:https://www.cnblogs.com/highfly2012/p/6080374.html

Android:Application

1.Application是程序真正的入口&#xff0c;启动时会先执行Application再执行其他组件。2.建立自己的Application类&#xff0c;需要在xml里将application修改自己的application类&#xff1a;<applicationandroid:name"com.example.aexh_19_application.MyApplication…

实体entity、JavaBean、Model、POJO、domain的区别

From: https://blog.csdn.net/u011665991/article/details/81201499 Java Bean、POJO、 Entity、 VO &#xff0c; 其实都是java 对象&#xff0c;只不过用于不同场合罢了。 按照 Spring MVC 分层结构&#xff1a; JavaBean: 表示层 &#xff08;Presentation Layer&#xf…

【Linux_Fedora_系统管理系列】_1_用户登录和系统初始配置

发现一个问题&#xff0c;在FC14 的Firefox浏览器中&#xff0c;编辑和排版好的博文&#xff0c;在windows下用chrome或者猎豹浏览器打开后&#xff0c;排版就变得阅读 不是很容易里&#xff0c;而且经常不经意的断行。不知道园子的管理人员时候注意到了这个问题。 Linux系统的…

HDU 2202 计算几何

最大三角形 Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4015 Accepted Submission(s): 1433 Problem Description老师在计算几何这门课上给Eddy布置了一道题目&#xff0c;题目是这样的&#xff1a;给定二维…

SpringBoot系列十:SpringBoot整合Redis

From: https://www.cnblogs.com/leeSmall/p/8728231.html 声明&#xff1a;本文来源于MLDN培训视频的课堂笔记&#xff0c;写在这里只是为了方便查阅。 1、概念&#xff1a;SpringBoot 整合 Redis 2、背景 Redis 的数据库的整合在 java 里面提供的官方工具包&#xff1a;j…

海贼王革命家—龙—实力到底如何?

龙——整个海贼王世界中最神秘的人物&#xff0c;令世界政府最担心的存在&#xff0c;是所有迷最为期待的实力展现&#xff0c;他的身上好像有着无数的秘密等着尾田为我们揭晓。 路飞的父亲——未来的海贼王、卡普的儿子——海军英雄、革民军首领——唯一可以跟世界政府抗衡的组…

python模块介绍- xlwt 创建xls文件(excel)

python模块介绍- xlwt 创建xls文件&#xff08;excel&#xff09; 2013-06-24磁针石 #承接软件自动化实施与培训等gtalk&#xff1a;ouyangchongwu#gmail.comqq 37391319 博客:http://blog.csdn.net/oychw #版权所有&#xff0c;转载刊登请来函联系 # 深圳测试自动化python项目…

SpringBoot(六):SpringBoot整合Redis

From: https://blog.csdn.net/plei_yue/article/details/79362372 前言 在本篇文章中将SpringBoot整合Redis&#xff0c;使用的是RedisTemplate&#xff0c;分别实现了SpringBoot与redis的单机版、集群版、哨兵模式的整合。 Maven依赖 <!-- 整合redis --> <…

[4]Telerik Grid 简单使用方法

1.columns <% Html.Telerik().Grid(Model).Name("Orders").Columns(columns >{//绑定列名columns.Bound(o > o.OrderID);//隐藏字段columns.Bound(o > o.OrderID).Hidden(true); //绑定列标题 columns.Bound(o > o.OrderDate).Title("…

Springboot 2.x版本 RedisCacheManager 类的配置,【与1.x 略有不同】

From: https://blog.csdn.net/qq_15071263/article/details/82897330 文章目录 Springboot 2.x版本 RedisCacheManager 类的配置&#xff0c;【与1.x 略有不同】 1、1.x 配置方式 2、2.x 配置方式 Springboot 2.x版本 RedisCacheMan…

.net应用程序中添加chm帮助文档打开显示此程序无法显示网页问题

在做.net大作业时添加了chm帮助文档结果在打开时显示“此程序无法显示网页问题”&#xff0c;但是把帮助文档拷到别的路径下却显示正常&#xff0c; 经过从网上查找&#xff0c;终于找到了答案&#xff1a; (1)、chm文件的路径中不能含有“#”“%”等字符&#xff0c;当含有这些…

新磁盘创建lvm并挂载

1 ### 1.查看硬盘2 fdisk -l3 4 ### 删除分区5 fdisk /dev/sdc6 ### 按d删除&#xff0c;按w保存并退出7 8 ### 创建pv9 pvcreate /dev/sdc 10 11 ### 创建 vg 12 vgcreate vg_hdp /dev/sdc 13 14 ### 创建 lv 15 lvcreate -L 200G -n lv_hdp vg_hdp 16 17 ### 格式化 lv 18…