Spring Boot實(shí)戰(zhàn)之?dāng)?shù)據(jù)庫操作的示例代碼
上篇文章中已經(jīng)通過一個(gè)簡單的HelloWorld程序講解了Spring boot的基本原理和使用。本文主要講解如何通過spring boot來訪問數(shù)據(jù)庫,本文會(huì)演示三種方式來訪問數(shù)據(jù)庫,第一種是JdbcTemplate,第二種是JPA,第三種是Mybatis。之前已經(jīng)提到過,本系列會(huì)以一個(gè)博客系統(tǒng)作為講解的基礎(chǔ),所以本文會(huì)講解文章的存儲(chǔ)和訪問(但不包括文章的詳情),因?yàn)樽罱K的實(shí)現(xiàn)是通過MyBatis來完成的,所以,對(duì)于JdbcTemplate和JPA只做簡單演示,MyBatis部分會(huì)完整實(shí)現(xiàn)對(duì)文章的增刪改查。
一、準(zhǔn)備工作
在演示這幾種方式之前,需要先準(zhǔn)備一些東西。第一個(gè)就是數(shù)據(jù)庫,本系統(tǒng)是采用MySQL實(shí)現(xiàn)的,我們需要先創(chuàng)建一個(gè)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;
后續(xù)的演示會(huì)對(duì)這個(gè)表進(jìn)行增刪改查,大家應(yīng)該會(huì)看到這個(gè)表里面并沒有文章的詳情,原因是文章的詳情比較長,如果放在這個(gè)表里面容易影響查詢文章列表的效率,所以文章的詳情會(huì)單獨(dú)存在另外的表里面。此外我們需要配置數(shù)據(jù)庫連接池,這里我們使用druid連接池,另外配置文件使用yaml配置,即application.yml(你也可以使用application.properties配置文件,沒什么太大的區(qū)別,如果對(duì)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
最后,我們還需要建立與數(shù)據(jù)庫對(duì)應(yīng)的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;
}
好了,需要準(zhǔn)備的工作就這些,現(xiàn)在開始實(shí)現(xiàn)數(shù)據(jù)庫的操作。
二、與JdbcTemplate集成
首先,我們先通過JdbcTemplate來訪問數(shù)據(jù)庫,這里只演示數(shù)據(jù)的插入,上一篇文章中我們已經(jīng)提到過,Spring boot提供了許多的starter來支撐不同的功能,要支持JdbcTemplate我們只需要引入下面的starter就可以了:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
現(xiàn)在我們就可以通過JdbcTemplate來實(shí)現(xiàn)數(shù)據(jù)的插入了:
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("測試標(biāo)題");
article.setSummary("測試摘要");
article.setUserId(1L);
article.setStatus(1);
article.setCreateTime(new Date());
article.setUpdateTime(new Date());
article.setPublicTime(new Date());
articleDao.insertArticle(article);
}
}
要支持上面的測試程序,也需要引入一個(gè)starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
從上面的代碼可以看出,其實(shí)除了引入jdbc的start之外,基本沒有配置,這都是spring boot的自動(dòng)幫我們完成了配置的過程。上面的代碼需要注意的Application類的位置,該類必須位于Dao類的父級(jí)的包中,比如這里Dao都位于com.pandy.blog.dao這個(gè)包下,現(xiàn)在我們把Application.java這個(gè)類從com.pandy.blog這個(gè)包移動(dòng)到com.pandy.blog.app這個(gè)包中,則會(huì)出現(xiàn)如下錯(cuò)誤:
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的實(shí)現(xiàn),這是什么原因呢?上一篇博文中我們已經(jīng)看到@SpringBootApplication這個(gè)注解繼承了@ComponentScan,其默認(rèn)情況下只會(huì)掃描Application類所在的包及子包。因此,對(duì)于上面的錯(cuò)誤,除了保持Application類在Dao的父包這種方式外,也可以指定掃描的包來解決:
@SpringBootApplication
@ComponentScan({"com.pandy.blog"})
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
三、與JPA集成
現(xiàn)在我們開始講解如何通過JPA的方式來實(shí)現(xiàn)數(shù)據(jù)庫的操作。還是跟JdbcTemplate類似,首先,我們需要引入對(duì)應(yīng)的starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
然后我們需要對(duì)POJO類增加Entity的注解,并指定表名(如果不指定,默認(rèn)的表名為article),然后需要指定ID的及其生成策略,這些都是JPA的知識(shí),與Spring boot無關(guān),如果不熟悉的話可以看下JPA的知識(shí)點(diǎn):
@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這個(gè)類,這里我們實(shí)現(xiàn)了兩個(gè)查詢方法,第一個(gè)是符合JPA命名規(guī)范的查詢,JPA會(huì)自動(dòng)幫我們完成查詢語句的生成,另一種方式是我們自己實(shí)現(xiàn)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("測試標(biāo)題");
assertTrue(articleList.size()>0);
}
}
注意,這里還是存在跟JdbcTemplate類似的問題,需要將Application這個(gè)啟動(dòng)類未于Respository和Entity類的父級(jí)包中,否則會(huì)出現(xiàn)如下錯(cuò)誤:
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
當(dāng)然,同樣也可以通過注解@EnableJpaRepositories指定掃描的JPA的包,但是還是不行,還會(huì)出現(xiàn)如下錯(cuò)誤:
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
這個(gè)錯(cuò)誤說明識(shí)別不了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來實(shí)現(xiàn)數(shù)據(jù)庫的訪問。同樣我們還是要引入starter:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
由于該starter不是spring boot官方提供的,所以版本號(hào)于Spring boot不一致,需要手動(dòng)指定。
MyBatis一般可以通過XML或者注解的方式來指定操作數(shù)據(jù)庫的SQL,個(gè)人比較偏向于XML,所以,本文中也只演示了通過XML的方式來訪問數(shù)據(jù)庫。首先,我們需要配置mapper的目錄。我們在application.yml中進(jìn)行配置:
mybatis: config-locations: mybatis/mybatis-config.xml mapper-locations: mybatis/mapper/*.xml type-aliases-package: com.pandy.blog.po
這里配置主要包括三個(gè)部分,一個(gè)是mybatis自身的一些配置,例如基本類型的別名。第二個(gè)是指定mapper文件的位置,第三個(gè)POJO類的別名。這個(gè)配置也可以通過 Java configuration來實(shí)現(xiàn),由于篇幅的問題,我這里就不詳述了,有興趣的朋友可以自己實(shí)現(xiàn)一下。
配置完后,我們先編寫mapper對(duì)應(yīng)的接口:
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);
}
該接口暫時(shí)只定義了四個(gè)方法,即添加、更新,以及根據(jù)ID查詢和分頁查詢。這是一個(gè)接口,并且和JPA類似,可以不用實(shí)現(xiàn)類。接下來我們編寫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>
最后,我們需要手動(dòng)指定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("測試標(biāo)題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);
}
}
五、總結(jié)
本文演示Spring boot與JdbcTemplate、JPA以及MyBatis的集成,整體上來說配置都比較簡單,以前做過相關(guān)配置的同學(xué)應(yīng)該感覺比較明顯,Spring boot確實(shí)在這方面給我們提供了很大的幫助。后續(xù)的文章中我們只會(huì)使用MyBatis這一種方式來進(jìn)行數(shù)據(jù)庫的操作,這里還有一點(diǎn)需要說明一下的是,MyBatis的分頁查詢在這里是手寫的,這個(gè)分頁在正式開發(fā)中可以通過插件來完成,不過這個(gè)與Spring boot沒什么關(guān)系,所以本文暫時(shí)通過這種手動(dòng)的方式來進(jìn)行分頁的處理。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- IntelliJ IDEA安裝運(yùn)行python插件方法
- Intellij IDEA安裝lombok插件及使用詳解
- IntelliJ IDEA 熱部署插件JRebel的使用
- 推薦一款I(lǐng)ntelliJ IDEA提示快捷鍵的Key Promoter X插件
- Java 程序員必備的 Intellij IDEA 插件
- IntelliJ IDEA JRebel 安裝使用圖文教程(熱部署插件)
- Intellij IDEA插件開發(fā)入門詳解
- Intellij Idea插件開發(fā)之創(chuàng)建項(xiàng)目層級(jí)的右鍵菜單
- 使用IntelliJ IDEA 2017.2.5 x64中的Spring Initializr插件快速創(chuàng)建Spring Boot/Cloud工程(圖解)
- 詳述IntelliJ IDEA插件的安裝及使用方法(圖解)
- IntelliJ IDEA 安裝vue開發(fā)插件的方法
- 詳解如何在IntelliJ IDEA中使用.ignore插件忽略不必要提交的文件
- Intellij IDEA 配置Subversion插件實(shí)現(xiàn)步驟詳解
- Spring jdbc中數(shù)據(jù)庫操作對(duì)象化模型的實(shí)例詳解
- springboot數(shù)據(jù)庫操作圖文教程
- Spring Boot Mysql 數(shù)據(jù)庫操作示例
- Spring Boot中使用IntelliJ IDEA插件EasyCode一鍵生成代碼詳細(xì)方法
相關(guān)文章
java?io文件操作從文件讀取數(shù)據(jù)的六種方法
這篇文章主要為大家介紹了java?io操作總結(jié)從文件讀取數(shù)據(jù)的六種方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-03-03
SpringBoot讀取資源目錄中JSON文件的方法實(shí)例
最近做項(xiàng)目遇到需要將json類型的配置文件引用到項(xiàng)目中,已經(jīng)將讀取json文件的方法封裝成工具類,下面這篇文章主要給大家介紹了關(guān)于SpringBoot讀取資源目錄中JSON文件的相關(guān)資料,需要的朋友可以參考下2023-04-04
mybatisPlus實(shí)現(xiàn)邏輯刪除,自動(dòng)生成創(chuàng)建時(shí)間和更新時(shí)間方式
MyBatisPlus框架中,通過@TableField(fill=FieldFill.INSERT)和@TableField(fill=FieldFill.UPDATE)注解可以實(shí)現(xiàn)在插入和更新時(shí)自動(dòng)填充字段,比如創(chuàng)建時(shí)間和更新時(shí)間,使用@TableLogic注解標(biāo)識(shí)邏輯刪除字段2024-09-09
Jackson忽略字段實(shí)現(xiàn)對(duì)字段進(jìn)行序列化和反序列化
在使用?Jackson?進(jìn)行序列化和反序列化時(shí),有時(shí)候需要對(duì)某些字段進(jìn)行過濾,以便在?JSON?數(shù)據(jù)中不包含某些敏感信息,下面就一起來了解一下Jackson忽略字段實(shí)現(xiàn)對(duì)字段進(jìn)行序列化和反序2023-10-10
Mybatis持久層框架入門之CRUD實(shí)例代碼詳解
這篇文章主要介紹了Mybatis持久層框架入門之CRUD實(shí)例,需要的朋友可以參考下2022-05-05
詳解使用Spring的restTemplete進(jìn)行Http請(qǐng)求
本篇文章主要介紹了詳解使用Spring的restTemplete進(jìn)行Http請(qǐng)求,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06

