以博客为演示项目背景,以用户模块和文章模块为演示的工程模块。
在dos窗口,执行以下命令:
mkdir mzblog
git init
效果如下:
<?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>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mazong</groupId>
<artifactId>server-blog</artifactId>
<version>0.1-SNAPSHOT</version>
<name>server-blog</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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
这个pom文件可以从别的项目复制过来,再修改一下。也可以创建一个SpringBoot项目,然后再把其他文件删除,保留创建的pom文件即可。
/*
Navicat MySQL Data Transfer
Source Server : 127.0.0.1
Source Server Version : 50718
Source Host : localhost:3306
Source Database : db_user
Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001
Date: 2019-12-11 20:23:18
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`UserName` varchar(128) DEFAULT '' COMMENT '名字',
`Age` tinyint(4) NOT NULL DEFAULT '0' COMMENT '年龄',
`CreateTime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `CreateTime` (`CreateTime`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COMMENT='用户信息';
-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'user1', '11', '2019-11-19 21:12:26');
INSERT INTO `tb_user` VALUES ('2', 'user2', '22', '2019-11-19 21:12:35');
INSERT INTO `tb_user` VALUES ('3', 'user3', '33', '2019-11-19 21:12:48');
INSERT INTO `tb_user` VALUES ('4', 'user4', '44', '2019-11-19 21:12:58');
INSERT INTO `tb_user` VALUES ('5', 'user5', '55', '2019-11-19 21:13:09');
INSERT INTO `tb_user` VALUES ('6', 'user6', '66', '2019-11-19 21:13:18');
INSERT INTO `tb_user` VALUES ('7', 'Tom', '99', '2019-12-02 20:14:12');
INSERT INTO `tb_user` VALUES ('8', 'leaf', '10', '2019-12-02 20:14:40');
INSERT INTO `tb_user` VALUES ('9', 'david', '10', '2019-12-02 21:12:32');
INSERT INTO `tb_user` VALUES ('10', 'david', '10', '2019-12-04 07:25:41');
/*
Navicat MySQL Data Transfer
Source Server : 127.0.0.1
Source Server Version : 50718
Source Host : localhost:3306
Source Database : db_article
Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001
Date: 2019-12-11 20:31:46
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb_article
-- ----------------------------
DROP TABLE IF EXISTS `tb_article`;
CREATE TABLE `tb_article` (
`aid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL DEFAULT '0' COMMENT '作者ID',
`Title` varchar(255) DEFAULT NULL COMMENT '文章标题',
`Head` tinytext COMMENT '文章简介',
`CreateTime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`aid`),
KEY `uid` (`uid`),
KEY `CreateTime` (`CreateTime`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='文章信息';
-- ----------------------------
-- Records of tb_article
-- ----------------------------
INSERT INTO `tb_article` VALUES ('1', '1', '你以为诺基亚死了,它却一跃成为全球5G巨头', '诺基亚曾经统治了智能手机行业,在iPhone和Android突然出现后,诺基亚被推下了悬崖。', '2019-12-03 14:09:28');
INSERT INTO `tb_article` VALUES ('2', '2', '疾风知劲草 中国经济坚定前行', '2019年,中国经济运行稳中有变、变中有忧,外部环境复杂严峻,经济面临下行压力。', '2019-12-03 14:12:04');
INSERT INTO `tb_article` VALUES ('3', '2', 'hello', 'world', '2019-12-04 08:26:53');
在这里,我们使用**MyBatis Plus**来做分页,因此我们额外增加下面依赖:
<!-- 分页插件 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
package com.mazong.serverbloguser.entity;
public class TbUser {
private int id;
private String UserName;
private int Age;
private String CreateTime;
// get
// set
// ...
}
package com.mazong.serverbloguser;
import com.mazong.serverbloguser.entity.TbUser;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
@Mapper
@Component(value = "iDbUserMapper")
public interface IDbUserMapper {
// select
@Select("SELECT * FROM tb_user WHERE id = #{id}")
TbUser getUserById(@Param("id") Integer id);
// insert
@Insert("INSERT INTO tb_user(UserName,Age) VALUES(#{UserName},#{Age})")
@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
int addUser(TbUser user);
// delete
void delUser(@Param("userId") Integer userId);
// update
@Update("UPDATE tb_user\n" +
"SET UserName=#{UserName},Age=#{Age}\n" +
"WHERE id=#{id}")
void updateUser(TbUser user);
}
## application.properties 文件
spring.application.name=server-blog-user
server.port=8000
## MyBatis 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/db_user?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
## mybatis
# 对应实体类的包名
mybatis.typeAliasesPackage=com.mazong.serverbloguser.mapper
# mapper.xml文件所在位置
# mybatis.mapperLocations=classpath:**/mapper/*.xml
logging.level.com.mazong.serverbloguser.mapper=debug
package com.mazong.serverbloguser.controller;
import com.mazong.serverbloguser.entity.TbUser;
import com.mazong.serverbloguser.mapper.IDbUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/")
public class UserController {
@Autowired
private IDbUserMapper iUserDbMapper;
@Autowired
HttpServletRequest request;
@RequestMapping(value = "/getUser")
@ResponseBody
public Object getUser(@RequestParam("id") Integer id) {
// http://localhost:8000/getUser?id=2
TbUser user = iUserDbMapper.getUserById(id);
return user;
}
@RequestMapping(value = "/addUser")
@ResponseBody
public String addUser(@RequestParam("userName") String userName, @RequestParam("age") int age) {
// http://localhost:8000/addUser
TbUser user = new TbUser();
user.setUserName(userName);
user.setAge(age);
int id = iUserDbMapper.addUser(user);
System.out.println("addUser="+user.getId());
return user.toString();
}
@RequestMapping(value = "/delUser")
@ResponseBody
public String getUserById(@RequestParam("id") Integer id) {
// http://localhost:8000/getUserById?userId=2
iUserDbMapper.delUser(id);
return String.format("delete id=%d", id);
}
@RequestMapping(value = "/updateUser")
@ResponseBody
public String updateUser(@RequestParam("id") int id, @RequestParam("userName") String userName, @RequestParam("age") int age) {
// http://localhost:8000/updateUser
TbUser user = new TbUser();
user.setId(id);
user.setUserName(userName);
user.setAge(age);
iUserDbMapper.updateUser(user);
System.out.println("updateUser="+user.getId());
return user.toString();
}
}
访问地址:
http://localhost:8000/getUser?id=2
创建工程的方法和设置,与创建server-blog-user工程的流程一样。
package com.mazong.serverblogarticle.entity;
public class TbArticle {
private int aid;
private int uid;
private String Title;
private String Head;
private String CreateTime;
// get
// set
// ...
}
package com.mazong.serverblogarticle.mapper;
import com.mazong.serverblogarticle.entity.TbArticle;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
@Mapper
@Component(value = "iDbArticleMapper")
public interface IDbArticleMapper {
// select
@Select("SELECT * FROM tb_article WHERE aid = #{id}")
TbArticle getArticle(@Param("id") Integer id);
// insert
@Insert("INSERT INTO tb_article(uid,Title,Head) VALUES(#{uid},#{Title},#{Head})")
@Options(useGeneratedKeys=true, keyProperty="aid", keyColumn="aid")
int addArticle(TbArticle article);
// delete
@Delete("DELETE FROM tb_article WHERE aid=#{aid}")
void delArticle(@Param("aid") Integer aid);
// update
@Update("UPDATE tb_article\n" +
"SET uid=#{uid},Title=#{Title},Head=#{Head}\n" +
"WHERE aid=#{id}")
void updateArticle(TbArticle article);
}
## application.properties
spring.application.name=server-blog-article
server.port=9000
## MyBatis 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/db_article?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# mybatis
# 对应实体类的包名
#mybatis.typeAliasesPackage=com.souyun.serverblogarticle.mapper
# mapper.xml文件所在位置,我放到了resources下面
#mybatis.mapperLocations=classpath:**/mapper/*.xml
logging.level.com.mazong.serverblogarticle.mapper=debug
package com.mazong.serverblogarticle.controller;
import com.mazong.serverblogarticle.entity.TbArticle;
import com.mazong.serverblogarticle.mapper.IDbArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/")
public class ArticleController {
@Autowired
private IDbArticleMapper iDbArticleMapper;
@Autowired
HttpServletRequest request;
@RequestMapping(value = "/getArticle")
@ResponseBody
public Object getArticle(@RequestParam("id") Integer id) {
// http://localhost:9000/getArticle?id=2
TbArticle article = iDbArticleMapper.getArticle(id);
return article;
}
}