springboot+vue+mybatis初学
效果图
前期准备
首先导入依赖
这里就把所有依赖附上了。
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
配置文件
application.yml
spring:
profiles:
active: dev
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test2?serverTimezone=UTC
username: root
password: 123456
mybatis:
type-aliases-package: com.example.demo.pojo
mapper-locations: classpath:mapper/*.xml
server:
port: 8080
logging:
level:
com.example.demo.dao: DEBUG
后端逻辑代码
建立各种package:dao,service,pojo,controller以及common(放一些封装的方法类或者一些常用的变量)
封装结果集
@Data
public class Result implements Serializable {
private int code;
private String msg;
private Object data;
public static Result succ(Object data){
return Result.succ(200,"操作成功",data);
}
public static Result succ(int code,String msg,Object data){
Result R=new Result();
R.setCode(code);
R.setMsg(msg);
R.setData(data);
return R;
}
public static Result fail(String msg){
return Result.fail(400,msg,null);
}
public static Result fail(int code,String msg,Object data){
Result R=new Result();
R.setCode(code);
R.setMsg(msg);
R.setData(data);
return R;
}
}
POJO
本次只是为了实现简单的前后端对接,所以建立一个简单的User类就可以了,当然数据库里已经建好了。
User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String name;
private String role;
}
Mapper
pojo类建好了,咱们就可以写下对应的增删改查方法
UserMapper接口
@Mapper
public interface UserMapper {
/**
* 查询所有对象
* @return
*/
List<User> queryUserList();
/**
* 根据Id查询用户信息
* @param id 用户ID
* @return
*/
User queryUserById(int id);
/**
* 根据任意信息查询用户信息
* @param user 用户
* @return
*/
User queryUserBy(User user);
/**
* 更新用户信息
* @param user 用户对象
* @return
*/
int updateUser(User user);
/**
* 删除用户信息
* @param id 用户id
* @return
*/
int deleteUser(int id);
/**
* 新增用户
* @param user 用户对象
* @return
*/
int insertUser(User user);
/**
* 分页查询用户列表
* @param map
* @return
*/
List<User> QuerypageUser(HashMap<String,Integer> map);
}
mapper接口弄好就要写一下对应的XML了。
UserMapper.xml
<resultMap id="userMap" type="User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="name" column="name"/>
<result property="role" column="role"/>
</resultMap>
<select id="queryUserList" resultType="User">
select *
from user
</select>
<select id="queryUserById" resultType="User" parameterType="int">
select *
from user
where id = #{id}
</select>
<select id="queryUserBy" resultType="User" parameterType="User">
select *
from user
<where>
<if test="id != null and id !=0">
id = #{id}
</if>
<if test="username != null">
and username = #{username,jdbcType=VARCHAR}
</if>
<if test="password != null">
and password = #{password,jdbcType=VARCHAR}
</if>
<if test="name != null">
and name = #{name},
</if>
<if test="role != null">
and role = #{role}
</if>
</where>
</select>
<insert id="insertUser" parameterType="User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username != null">
username,
</if>
<if test="password != null">
password,
</if>
<if test="name != null">
name,
</if>
<if test="role != null">
role
</if>
</trim>
values
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username != null">
#{username},
</if>
<if test="password != null">
#{password},
</if>
<if test="name != null">
#{name},
</if>
<if test="role != null">
#{role}
</if>
</trim>
</insert>
<update id="updateUser" parameterType="User">
update user
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="role != null">
role = #{role,jdbcType=VARCHAR}
</if>
</set>
where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete
from user
where id = #{id}
</delete>
Service
UserService接口
public interface UserService {
List<User> queryUserList();
User queryUserById(int id);
User queryUserBy(User user);
int updateUser(User user);
int deleteUser(int id);
int insertUser(User user);
List<User> pageUser(int currentPage,int pageSize);
}
UserServiceImpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> queryUserList(){
return userMapper.queryUserList();
};
@Override
public User queryUserById(int id){
return userMapper.queryUserById(id);
};
@Override
public User queryUserBy(User user){
return userMapper.queryUserBy(user);
};
@Override
public int updateUser(User user){
return userMapper.updateUser(user);
};
@Override
public int deleteUser(int id){
return userMapper.deleteUser(id);
};
@Override
public int insertUser(User user){
return userMapper.insertUser(user);
}
@Override
public List<User> pageUser(int currentPage, int pageSize) {
HashMap<String, Integer> map = new HashMap();
map.put("r",0+(currentPage-1)*pageSize);
map.put("l",pageSize);
return userMapper.QuerypageUser(map);
}
}
Controller
UserController
@RestController
@RequestMapping("/testUser")
public class UserController {
@Autowired
UserService userService;
//查询所有用户列表
@RequestMapping("/query")
public List<User> getUserInfo(){
List<User> users = userService.queryUserList();
return users;
}
//通过Id查询当前用户所有信息
@GetMapping("/query/{id}")
public User getUserInfoById(@PathVariable int id){
User user = userService.queryUserById(id);
return user;
}
//新增用户信息
//http://localhost:8080/testUser/save?username=1&password=2&name=3&role=VIP9
@GetMapping("/save")
public String saveUser(User user){
int result = userService.insertUser(user);
if(result>0){
return "新增成功";
}else {
return "新增失败";
}
}
//更新用户信息
//http://localhost:8080/testUser/modify?id=17&username=asd&password=22222&name=mmc&role=VIP9
@GetMapping("/modify")
public String modifyUser(User user){
int result = userService.updateUser(user);
if(result>0){
return "更新成功";
}else {
return "更新失败";
}
}
//删除用户信息
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable int id){
int result = userService.deleteUser(id);
if(result>0){
return "删除成功";
}else {
return "删除失败";
}
}
//登录接口
@PostMapping("/login")
@ResponseBody
public Result Login(@RequestBody User requestUser){
User user = userService.queryUserBy(requestUser);
Result res;
if(user!=null){
res = Result.succ(user);
}else {
res = Result.fail("用户名密码错误");
}
return res;
}
//分页查询用户列表
@GetMapping("/users/{currentPage}/{pageSize}")
@ResponseBody
public Result Users(@PathVariable int currentPage,
@PathVariable int pageSize){
List<User> users = userService.pageUser(currentPage,pageSize);
int total = userService.queryUserList().size();
HashMap<String,Object> map = new HashMap<>();
map.put("list",users);
map.put("total",total);
map.put("currentPage",currentPage);
map.put("pageSize",pageSize);
Result res;
if(users == null){
res = Result.fail("数据查询失败");
}else {
res = Result.succ(map);
}
return res;
}
}
前端代码
前端使用的Vue,先快速建立个Vue项目。
- ①安装node.js,下载相应版本的node.js,下载地址:https://nodejs.org/en/download/,下载完双击安装,点击下一步直到安装完成
- ② 安装完成后,附件里选择命令提示符(或者在开始的搜索框里输入cmd回车调出命令面板)输入:node -v回车,出现相应版本证明安装成功, node环境已经安装完成,由于有些npm有些资源被屏蔽或者是国外资源的原因,经常会导致用npm安装依赖包的时候失败,所有我还需要npm的 国内镜像—cnpm。在命令行中输入:npm install -g cnpm –registry=https://registry.npm.taobao.org回车,大约需要3分钟, 如果报错或没反应,则卸掉node.js重新安装
- ③ 安装全局vue-cli脚手架,用于帮助搭建所需的模板框架。输入命令:cnpm install -g vue-cli回车等待完成。
- ④ 创建项目,首先我们要选定目录,然后再命令行中把目录转到选定的目录,假如我们打算把项目新建在e盘下的vue文件夹中则输入下面的命令: e:回车,然后cd vue,然后输入命令:vue init webpack 项目文件夹名称,回车,运行初始化命令的时候会让用户输入几个基本的选项, 如项目名称,描述,作者等信息,如果不想填直接回车默认就好。(一顿回车+N键就完成了)
- ⑤ 安装项目所需的依赖包,首先输入:cd 项目名回车,然后输入:cnpm install回车等待安装,安装完成之后,会在我们的项目目录firstVue 文件夹中多出一个node_modules文件夹,这里边就是我们项目需要的依赖包资源。安装完依赖包之后,就可以运行整个项目了。
- ⑥ 测试环境是否搭建成功,在cmd里输入:cnpm run dev回车,项目运行成功后,浏览器会自动打开localhost:8080(如果浏览器没有自动打开 ,可以手动输入)。运行成功后,会看到Welcome to Your Vue.js App页面。
vue配置
config下的index文件配置下端口以及访问后端的网址和端口的封装
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
loglevel:'debug',
pathRewrite: {
'^/api': '',
}
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8888, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
}
建个view包用来放vue页面,并且把axios,Element UI npm安装下来
登录页面
login.vue
<template>
<div>
<el-container>
<el-header>
<img class="mlogo" src="../assets/logo.png" />
</el-header>
<el-main>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="用户名" prop="username">
<el-input v-model="ruleForm.username"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input type="password" v-model="ruleForm.password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</el-main>
</el-container>
</div>
</template>
<script>
export default {
name: "Login",
data() {
return {
ruleForm: {
username: '',
password: ''
},
rules: {
username: [{
required: true,
message: "请输入用户名",
trigger: "blur"
},
{
min: 3,
max: 15,
message: "长度在 3 到 15 个字符",
trigger: "blur"
},
],
password: [{
required: true,
message: "请输入密码",
trigger: "change"
}, ]
},
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert("submit!");
this.$http.post("/api/testUser/login",
{
username: this.ruleForm.username,
password: this.ruleForm.password,
})
.then(res =>{
console.log(res.data)
if(res.data.code==200){
setTimeout(() => {this.$router.push({ path: '/Content' });}, 1500);
}
})
} else {
console.log("error submit!!");
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
},
};
</script>
<style scoped>
.el-header,
.el-footer {
/*background-color: #b3c0d1;*/
color: #333;
text-align: center;
line-height: 60px;
}
.el-aside {
background-color: #d3dce6;
color: #333;
text-align: center;
line-height: 200px;
}
.el-main {
/* background-color: #e9eef3; */
color: #333;
text-align: center;
line-height: 160px;
}
body>.el-container {
margin-bottom: 40px;
}
.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
line-height: 260px;
}
.el-container:nth-child(7) .el-aside {
line-height: 320px;
}
.mlogo {
margin-top: 5px;
height: 60px;
}
.demo-ruleForm{
margin: 0 auto;
max-width: 500px;
}
</style>
用户列表页面
跳转的页面:
Content.vue
<template>
<div id="Content">
<el-container>
<el-header>
<span class="tspan">用户列表</span>
</el-header>
<el-main>
<el-table
:data="tableData"
height="500"
border
>
<el-table-column
prop="id"
label="ID号"
width="200">
</el-table-column>
<el-table-column
prop="username"
label="用户名"
width="200">
</el-table-column>
<el-table-column
prop="password"
label="密码"
width="200">
</el-table-column>
<el-table-column
prop="name"
label="名字"
width="200">
</el-table-column>
<el-table-column
prop="role"
label="角色"
width="200">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
width="200">
<template #default="scope">
<el-button
size="mini"
@click="handleEdit(scope.$index, scope.row)">编辑
</el-button>
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.$index, scope.row)">删除
</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
background
layout="prev, pager, next"
:current-page=currentPage
:page-size=pageSize
:total=total
@current-change=page
>
</el-pagination>
</el-main>
</el-container>
</div>
</template>
<script>
export default {
name: 'Content',
data() {
return {
tableData: [{}],
currentPage: 1,
total: 0,
pageSize: 3
}
},
methods:{
page(currentPage){
const _this = this
_this.$http.get("/api/testUser/users/" + currentPage +"/"+ _this.pageSize).then(res =>{
console.log(res)
_this.tableData = res.data.data.list
_this.currentPage = res.data.data.currentPage
_this.pageSize = res.data.data.pageSize
_this.total = res.data.data.total
})
}
},
created(){
this.page(1,3)
}
}
</script>
<style>
.el-header,
.el-footer {
/*background-color: #b3c0d1;*/
color: #333;
text-align: center;
line-height: 60px;
}
.el-aside {
background-color: #d3dce6;
color: #333;
text-align: center;
line-height: 200px;
}
.el-main {
/*background-color: #e9eef3;*/
color: #333;
text-align: center;
line-height: 160px;
height: 700px;
}
body > .el-container {
margin-bottom: 40px;
}
.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
line-height: 260px;
}
.el-container:nth-child(7) .el-aside {
line-height: 320px;
}
.el-table{
margin: 0 auto;
width: 70%;
}
</style>