入门案例
使用Springboot实现对数据库的增删改查
SpringBoot整合案例思路
SpringBoot集成MyBatis,redis,Dubbo,Thymeleaf
1.Dubbo分布式框架要求至少是三个工程:接口工程,服务提供者,服务消费者
2.接口工程:实体bean和业务serviceimpl接口
3.服务提供者:集成MyBatis,它也是实现了业务的接口,该工程只用到了Spring,MyBatis,Redis
4.服务消费者:集成Thymeleaf,它使用了SpringMVC,spring
网盘:项目资料
1. 前期准备
1.1软件安装
redis官网下载
Apache ZooKeeper注册中心
mysql-connector-java驱动
数据库Tomcat
客户端SQLyog Community
1.2创建数据库、学生信息表
可使用如下代码块生成: 做成sql脚本,导入SQLyog中直接生成
`
drop table if exists t_student;
create table t_student
(
id int(10) not null auto_increment,
name varchar(20) null,
age int(10) null,
constraint PK_T_STUDENT primary key clustered (id)
);
insert into t_student(name,age) values(“zhangsan”,25);
insert into t_student(name,age) values(“lisi”,28);
insert into t_student(name,age) values(“wangwu”,23);
insert into t_student(name,age) values(“Tom”,21);
insert into t_student(name,age) values(“Jck”,55);
insert into t_student(name,age) values(“Lucy”,27);
insert into t_student(name,age) values(“zhaoliu”,75);`
创建数据库xw
学生信息表t-studen
2. Maven工程多模块管理
2.1 创建父工程
打开IDEA ,新建一个空项目project,再往里面添加四个工程module
接口工程为普通 maven工程,消费者、提供者为pringboot工程
2.2创建子工程(接口工程、提供者工程、消费者工程)
工程结构
3. 添加依赖
3.1 父工程pom
<?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>
<modules>
<module>../springboot-interface</module>
</modules>
<!-- 让父工程成为,pringboot工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xw</groupId>
<artifactId>springboot-parent</artifactId>
<packaging>pom</packaging>
<version>1.0.0</version>
<!-- 版本号管理,管理未管理的依赖(带有版本号),自己建的工程,不需要管理 -->
<properties>
<java.version>15</java.version>
<dubbo-spring-boot-starter-version>2.0.0</dubbo-spring-boot-starter-version>
<zkClient-version>0.9</zkClient-version>
<mybatis-spring-boot-starter-version>2.0.0</mybatis-spring-boot-starter-version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>${dubbo-spring-boot-starter-version}</version>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>${zkClient-version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter-version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
接口工程pom:
<?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">
<parent>
<artifactId>springboot-parent</artifactId>
<groupId>com.xw</groupId>
<version>1.0.0</version>
<relativePath>../springboot-parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springboot-interface</artifactId>
</project>
提供者pom:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>springboot-parent</artifactId>
<groupId>com.xw</groupId>
<version>1.0.0</version>
<relativePath>../springboot-parent/pom.xml</relativePath>
</parent>
<artifactId>springboot-provider</artifactId>
<name>springboot-provider</name>
<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>
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.xw</groupId>
<artifactId>springboot-interface</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- mybatis代码自动生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!-- 文件位置-->
<configurationFile>GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
4. 编写代码
4.1 开发 提供者
mybatis逆向工程(GeneratorMapper文件+自动生成插件),生成mapper+mapper映射文件+实体beam类(放在接口工程下面)
GeneratorMapper.xml 如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 -->
<classPathEntry location="D:\java\mysql-connector-java-8.0.23.jar"/>
<!-- 配置 table 表信息内容体, targetRuntime 指定采用 MyBatis3 的版本 -->
<context id="tables" targetRuntime="MyBatis3">
<!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/xw"
userId="root"
password="123456">
</jdbcConnection>
<!-- 生成 model 类, targetPackage 指定 model 类的包名, targetProject 指定
生成的 model 放在 IDEA 的哪个工程下面-->
<javaModelGenerator targetPackage="com.xw.springbootinterface.model"
targetProject="D:\java\works\springboot\SpringBoot-Dubbo-MyBatis-Redis-Thymeleaf\springboot-interface\src\main\java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成 MyBatis 的 Mapper.xml 文件, targetPackage 指定 mapper.xml 文件的
包名, targetProject 指定生成的 mapper.xml 放在 IDEA 的哪个工程下面 -->
<sqlMapGenerator targetPackage="com.xw.springbootprovider.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包
名, targetProject 指定生成的 Mapper 接口放在 IDEA 的哪个工程下面 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.xw.springbootprovider.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 数据库表名及对应的 Java 模型类名 有多少个表 有多少个table-->
<table tableName="t_student" domainObjectName="Student"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
注意问题
1 需要将 model beam类放在 interface 过程下面,地址可以用绝对地址
2 需要将 接口工程、父工程发布(install )到本地maven仓库(properties)才可以找到maven依赖
3 实体类 序列化
4.2 提供者配置文件
application-dev.properties 如下:
server.port=8081
server.servlet.context-path=/
# 数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/xw?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
# dubbo
spring.application.name=springboot-provider
spring.dubbo.server=true
spring.dubbo.registry=zookeeper://localhost:2181
# redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=123456
使用多环境管理时,需要写多个环境配置文件,只需将主配置文件激活具体哪个环境即可
主配置文件application.properties如下:
spring.profiles.active=dev
4.3 提供者 自动生成的 mapper 及其 映射文件
StudentMapper 如下:
package com.xw.springbootprovider.mapper;
import com.xw.springbootinterface.model.Student;
public interface StudentMapper {
int deleteByPrimaryKey(Integer id);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
Integer selectAllStudentCount();
}
StudentMapper.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.xw.springbootprovider.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.xw.springbootinterface.model.Student">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
<sql id="Base_Column_List">
id, name, age
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_student
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from t_student
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.xw.springbootinterface.model.Student">
insert into t_student (id, name, age
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
)
</insert>
<insert id="insertSelective" parameterType="com.xw.springbootinterface.model.Student">
insert into t_student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.xw.springbootinterface.model.Student">
update t_student
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.xw.springbootinterface.model.Student">
update t_student
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="selectAllStudentCount" resultType="java.lang.Integer">
select count(*) from t_student
</select>
</mapper>
4.4 提供者 主程序
package com.xw.springbootprovider;
import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.xw.springbootprovider.mapper")
@EnableDubboConfiguration // 开启 dubbo
public class SpringbootProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootProviderApplication.class, args);
}
}
4.5 接口工程
自动生成的beam实体类Student如下:
package com.xw.springbootinterface.model;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
业务接口StudentService 如下:
package com.xw.springbootinterface.service;
import com.xw.springbootinterface.model.Student;
public interface StudentService {
Student queryStudentById(Integer id);
Integer queryAllStudentCount();
}
5.6 消费者工程
主配置文件application.properties
spring.profiles.active=dev
application-dev.properties 配置文件如下:
server.port=8083
server.servlet.context-path=/
# dubbo
spring.application.name=springboot-consumer
spring.dubbo.registry=zookeeper://localhost:2181
# thymeleaf 关缓存
spring.thymeleaf.cache=false
# thymeleaf 前后缀
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 字符编码
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
server.servlet.encoding.charset=utf-8
控制类 如下;
package com.xw.springbootconsumer.web;
import com.alibaba.dubbo.config.annotation.Reference;
import com.xw.springbootinterface.model.Student;
import com.xw.springbootinterface.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class StudentController {
// 测试方法
@RequestMapping("/demo")
public @ResponseBody String say(){
return "nihao";
}
// 查询学生
@Reference(interfaceClass = StudentService.class,version = "1.0.0",check = false)
private StudentService studentService;
@RequestMapping(value = "/student/detail/{id}")
public String studentDetail(Model model,
@PathVariable("id") Integer id){
Student student = studentService.queryStudentById(id);
model.addAttribute("student",student);
return "studentDetail";
}
// 获取学生总人数 使用到redis
@RequestMapping(value = "/student/count")
public @ResponseBody Object allStudentCount(){
Integer allStudentCount = studentService.queryAllStudentCount();
return allStudentCount;
}
}
主程序如下:
package com.xw.springbootconsumer;
import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableDubboConfiguration
public class SpringbootConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootConsumerApplication.class, args);
}
}
显示页面 studentDetail.html 如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>学生详情</title>
</head>
<body>
学生编号:<span th:text="${student.id}"/><br/>
学生姓名:<span th:text="${student.name}"/><br/>
学生年龄:<span th:text="${student.age}"/><br/>
</body>
</html>
5. 实验结果
启动 privider
启动 consumer
浏览器输入地址
结果:
6. 附录
附录:启动 dubbo redis 服务
Dubbo
Redis 密码 123456 在启动测试后可以 输入 auth “123456” 是看效果
【更多完整功能!!!待续】
doc版