前言

通过上一章的学习,我们已经对SpringBoot有简单的入门,接下来我们深入学习一下SpringBoot,我们知道任何一个网站的数据大多数都是动态的,也就是说数据是从数据库提取出来的,而非静态数据,那么我们接下来就是要连接数据库,现在我们经常使用的数据库的种类可以大致分为两种,关系型数据库和非关系型数据库,而MySQL数据库,Oracle数据库SQL Server数据库等都是关系型数据库,而Redis,Mongodb等都是非关系型数据库。

本章目标

  • 使用SpringBoot和MyBatis通过注解的方式操作数据库

  • 使用SpringBoot和MyBatis通过XML配置文件的方式操作数据库

项目搭建

1.打开idea,选择Create New Project

2.选择Spring Initializer,然后点击Next

3.填写组织,坐标等信息,然后点击Next

4.选择依赖Web,然后勾选Web,之后一直Next下去,直到项目构建完成

5.项目结构搭好之后,我们新建一些目录分为控制层,服务层,数据访问层,实体层,完整结构如下

6.由于我们要使用MyBatis操作数据库,所以需要添加一些依赖,完整的pom.xml文件如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo02</groupId>
<artifactId>demo_02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo_02</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis-spring适配器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

7.接下来我们需要新建数据库以及生成实体,数据的建立我就不重复多说了,说一下使用idea快速生成实体(Product),数据库的sql脚本如下

#创建商品信息表
create table product
(
pid int primary key not null auto_increment COMMENT"商品编号",
pname varchar(50) COMMENT"商品名称",
pprice DECIMAL(10,2) COMMENT"商品价格",
ptime varchar(50) COMMENT"入库时间",
pcount int COMMENT"库存",
pstatus int COMMENT"商品状态" #0 代表下架,1代表上架
)COMMENT"商品信息表" insert into product(pname,pprice,ptime,pcount,pstatus)VALUES
("苹果",11,"2019-10-1",11,1) SELECT * from product

8.Database表示要连接的数据库名称,User表示用户名称,Password表示密码,然后点击Ok,然后选择你要生成实体的目录,生成完成之后基本结构就搭建好了

9.Product实体代码如下

package com.ssm.entity;
/*
* 商品实体类
* */
public class Product { private long pid;//编号
private String pname;//名称
private double pprice;//价格
private String ptime;//入库时间
private long pcount;//数量
private long pstatus;//状态
//无参构造方法
public Product() {}
//带参构造方法
public Product(long pid, String pname, double pprice, String ptime, long pcount, long pstatus) {
this.pid = pid;
this.pname = pname;
this.pprice = pprice;
this.ptime = ptime;
this.pcount = pcount;
this.pstatus = pstatus;
} public long getPid() {
return pid;
} public void setPid(long pid) {
this.pid = pid;
} public String getPname() {
return pname;
} public void setPname(String pname) {
this.pname = pname;
} public double getPprice() {
return pprice;
} public void setPprice(double pprice) {
this.pprice = pprice;
} public String getPtime() {
return ptime;
} public void setPtime(String ptime) {
this.ptime = ptime;
} public long getPcount() {
return pcount;
} public void setPcount(long pcount) {
this.pcount = pcount;
} public long getPstatus() {
return pstatus;
} public void setPstatus(long pstatus) {
this.pstatus = pstatus;
} @Override
public String toString() {
return "Product{" +
"pid=" + pid +
", pname='" + pname + '\'' +
", pprice=" + pprice +
", ptime='" + ptime + '\'' +
", pcount=" + pcount +
", pstatus=" + pstatus +
'}';
}
}

SpringBoot整合MyBatis基于注解

1.接下来,我们就需要配置一下连接数据库的配置文件,在application.xml中进行配置,applicaion.xml文件如下

#连接数据库的驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#连接数据库的url
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
#用户名
spring.datasource.username=root
#密码
spring.datasource.password=123456

2.现在我们就可以操作数据库了,编写ProductDao,ProductService,ProductImple,ProductController以及配置SpringBoot主程序,由于我们新建的包不是和SpringBoot主程序同级目录,所以无法扫描到。项目启动时,只有@SpringBootApplication 所在的包下面才能被扫描到,启动类是MainApplication.java, 也就是MainApplication.java类所在的这个包,而其他的controller和service以及mapper在其他的包里,所以并没有被扫描。所以我们需要配置一下

3.ProductDao文件如下

package com.ssm.dao;

import com.ssm.entity.Product;
import org.apache.ibatis.annotations.Select; import java.util.List; public interface ProductDao {
@Select("select * from product")
List<Product> findAllProduct();
}

4.ProductService文件如下

package com.ssm.service;

import com.ssm.entity.Product;

import java.util.List;

public interface ProductService {
List<Product> findAllProduct();
}

5.ProductImple文件如下

package com.ssm.service.imple;

import com.ssm.dao.ProductDao;
import com.ssm.entity.Product;
import com.ssm.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class ProductImple implements ProductService {
@Autowired
private ProductDao productDao;
@Override
public List<Product> findAllProduct() {
return productDao.findAllProduct();
}
}

6.ProductController文件如下

package com.ssm.controller;

import com.ssm.entity.Product;
import com.ssm.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController
public class ProductController {
@Autowired
private ProductService productService;
//查询全部的商品信息
@GetMapping("/product")
public List<Product> findAllProduct(){
return productService.findAllProduct();
}
}

7.SpringBoot主程序文件如下

package com.demo02.demo_02;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; @SpringBootApplication
@ComponentScan(basePackages = {"com.ssm.controller","com.ssm.service"})
@MapperScan(basePackages = {"com.ssm.dao"})
public class Demo02Application { public static void main(String[] args) {
SpringApplication.run(Demo02Application.class, args);
} }

8.点击运行,在地址栏输入localhost:8080/product,出现如下结果

SpringBoot整合MyBatis基于XML配置文件

1.现在我们通过第二种方式操作数据库,我们先将application.xml中的配置文件全部注释,然后新建applicaion.yml,为什么要使用这种格式呢?因为这种方式方便简洁,官方也推荐我们使用这种类型,这是一些的相关格式。

server:
port: 8801
eureka:
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://localhost:8801/eureka/

2.applicaion.yml配置如下

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
username: root
password: 123456
mybatis:
typeAliasesPackage: com.ssm.entity
mapperLocations: classpath:mapper/*Mapper.xml

3.我们要通过xml的格式操作数据库也就是我们需要写Mapper.xml文件,在src/main/resources新建Mapper文件夹,然后新建ProductMapper.xml

4.ProductMapper.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.ssm.dao.ProductDao">
<!--查询全部商品信息-->
<select id="findAllProduct" resultType="product">
select * from product
</select>
</mapper>

5.ProductDao文件如下

package com.ssm.dao;
import com.ssm.entity.Product;
import org.apache.ibatis.annotations.Select; import java.util.List; public interface ProductDao {
// @Select("select * from product")
List<Product> findAllProduct();
}

6.ProductService文件如下

package com.ssm.service;

import com.ssm.entity.Product;

import java.util.List;

public interface ProductService {
List<Product> findAllProduct();
}

7.ProductImple文件如下

package com.ssm.service.imple;

import com.ssm.dao.ProductDao;
import com.ssm.entity.Product;
import com.ssm.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class ProductImple implements ProductService {
@Autowired
private ProductDao productDao;
@Override
public List<Product> findAllProduct() {
return productDao.findAllProduct();
}
}

8.ProductController文件如下

package com.ssm.controller;

import com.ssm.entity.Product;
import com.ssm.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController
public class ProductController {
@Autowired
private ProductService productService;
//查询全部的商品信息
@GetMapping("/product")
public List<Product> findAllProduct(){
return productService.findAllProduct();
}
}

9.SpringBoot主程序文件如下

package com.demo02.demo_02;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; @SpringBootApplication
@ComponentScan(basePackages = {"com.ssm.controller","com.ssm.service"})
@MapperScan(basePackages = {"com.ssm.dao"})
public class Demo02Application { public static void main(String[] args) {
SpringApplication.run(Demo02Application.class, args);
} }

10.运行,结果和之前的一样

结尾

通过对本章的学习,我们已经学会了SpringBoot整合MyBatis的两种方式,相对SSM框架来说,SpringBoot的确简化了我们许多操作,当你需要哪些依赖时,我们直接选择就可以,它也的确比较实在。

SpringBoot从入门到精通二(SpringBoot整合myBatis的两种方式)的更多相关文章

  1. springboot整合mybatis的两种方式

    https://blog.csdn.net/qq_32719003/article/details/72123917 springboot通过java bean集成通用mapper的两种方式 前言:公 ...

  2. SpringBoot整合Servlet的两种方式

    SpringBoot整合Servlet有两种方式: 1.通过注解扫描完成Servlet组件的注册: 2.通过方法完成Servlet组件的注册: 现在简单记录一下两种方式的实现 1.通过注解扫描完成Se ...

  3. 【SpringBoot】05.SpringBoot整合Listener的两种方式

    SpringBoot整合Listener的两种方式: 1.通过注解扫描完成Listener组件的注册 创建一个类实现ServletContextListener (具体实现哪个Listener根据情况 ...

  4. 【SpringBoot】03.SpringBoot整合Servlet的两种方式

    SpringBoot整合Servlet的两种方式: 1. 通过注解扫描完成Servlet组件注册 新建Servlet类继承HttpServlet 重写超类doGet方法 在该类使用注解@WebServ ...

  5. springboot项目启动成功后执行一段代码的两种方式

    springboot项目启动成功后执行一段代码的两种方式 实现ApplicationRunner接口 package com.lnjecit.lifecycle; import org.springf ...

  6. Spring Boot 整合 Shiro ,两种方式全总结!

    在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...

  7. 【SpringBoot】04.SpringBoot整合Filter的两种方式

    SpringBoot整合Filter过滤器的两种方式: 1.通过扫描注解完成Filter组件注册 创建一个类,实现Filter接口,实现doFilter()方法 在该类使用注解@WebFilter,设 ...

  8. SpringCloud系列-整合Hystrix的两种方式

    Hystrix [hɪst'rɪks],中文含义是豪猪,因其背上长满棘刺,从而拥有了自我保护的能力.本文所说的Hystrix是Netflix开源的一款容错框架,同样具有自我保护能力. 本文目录 一.H ...

  9. Spring Boot 2.x(四):整合Mybatis的四种方式

    前言 目前的大环境下,使用Mybatis作为持久层框架还是占了绝大多数的,下面我们来说一下使用Mybatis的几种姿势. 姿势一:零配置注解开发 第一步:引入依赖 首先,我们需要在pom文件中添加依赖 ...

随机推荐

  1. Python 金融数据分析 (一)—— 股票数据

    1. tushare 库 tushare 的官网请见:TuShare -财经数据接口包,是国人自己开发的 Python 爬数据工具(所谓的爬,自然就是在线连网获取数据),囊括股票.期货.宏观经济.电影 ...

  2. UWP 中的各种文件路径(用户、缓存、漫游、安装……)

    原文 UWP 中的各种文件路径(用户.缓存.漫游.安装……) UWP 提供了多种不同文件路径访问方式,对应到不同的文件路径中.可能我们只是简单用 ApplicationData.Current 获取一 ...

  3. [转]完美解决)Tomcat启动提示At least one JAR was scanned for TLDs yet contained no TLDs

    一.文章前言    本文是亲测有效解决At least one JAR was scanned for TLDs yet contained no TLDs问题,绝对不是为了积分随便粘贴复制然后压根都 ...

  4. python_简单的DB统计

    import numpy as npimport pylab as pldates=['20170314','20170315','20170316','20170317','20170318','2 ...

  5. Spring MVC 专题

    Spring静态资源路径是指系统可以直接访问的路径,且路径下的所有文件均可被用户直接读取.在Springboot中默认的静态资源路径有:classpath:/META-INF/resources/,c ...

  6. XF 标签页面

    using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation (XamlCompila ...

  7. 在mac中如何清除.svn文件

    有些时候在开发一个应用程序我们需要用到版本控制,它可以帮助我们很好的控制我们程序的代码,尤其在多人开发的时候,优点尤为突出. 但是在有些情况下我们又认为这些.svn真的很麻烦,那么我们怎么把他们一下子 ...

  8. 【C#】WindowsAPICodePack-Shell使用教程

    原文:[C#]WindowsAPICodePack-Shell使用教程 1.首先在项目中添加WindowsAPICodePack的Nuget包.   点击安装即可. 2.获取<我的电脑>的 ...

  9. https://www.jianshu.com/p/4da29fa310d2

    wampserver显示红色.橙色的解决方案   拿笔的小鑫 关注 2016.10.15 14:38* 字数 2643 阅读 5083评论 0喜欢 3赞赏 1 </br></br&g ...

  10. 百度蜘蛛ip段代表的不同含义

    有时候我们在分析百度蜘蛛的时候,会发现很多的ip,这些个ip地址,根据后面的参数可以发现都是百度的.刚学习SEO不久的同学肯定要问:这些ip地址到底代表什么含义,是不是不同的ip地址所代表的含义不一样 ...