在Spring boot项目中使用 mybatis 与Vue实现对数据进行增删改查操作

发布时间:2020-11-20 16:25:58 作者:Leah
来源:亿速云 阅读:188

在Spring boot项目中使用 mybatis 与Vue实现对数据进行增删改查操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

pom文件

<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>
 <groupId>com.imooc</groupId>
 <artifactId>demo</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 <name>demo</name>
 <description>Demo project for Spring Boot</description>
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>1.4.3.RELEASE</version>
 <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 <java.version>1.8</java.version>
 </properties>
 <dependencies>
 <dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.1.1</version>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
 </dependency>
 <dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.1.1</version>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-redis</artifactId>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-activemq</artifactId>
 </dependency>
 <!--http://localhost:8080/health-->
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
 </dependency>
 <dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>4.1.6</version>
 </dependency>
 </dependencies>
 <build>
 <plugins>
  <plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  </plugin>
 </plugins>
 </build>
</project>

接下来是yml文件,主要加入了mybatis的配置,以及sql的打印

spring:
 datasource:
 name: test
 url: jdbc:mysql://localhost/imooc&#63;useUnicode=true&characterEncoding=utf-8&useSSL=false
 username: root
 password: 123456
 driver-class-name: com.mysql.jdbc.Driver
mybatis:
 type-aliases-package: com.imooc.model
 mapper-locations: classpath:mybatis/mapper/*.xml
 check-config-location: true
 config-location: classpath:mybatis/mybatis-config.xml
logging:
 level:
 com.imooc.repository: debug
 com.imooc.service.impl: debug
 com.imooc.controller: debug
 com.imooc.activemq: debug

接下来是repositpry文件

@Repository
public interface UserRepository {
 List<User> findUsersByUsername(@Param("username") String username);
 int getCount();
 int saveUser(User user);
 int modifyUser(User user);
 int removeUser(@Param("userId") int userId);
}

service文件

@Service
public class UserServiceImpl implements UserService {
 @Autowired
 private UserRepository userRepository;
 @Override
 public Map<String, Object> getTableData(int pageNum, int pageSize, String username) {
 try {
  PageHelper.startPage(pageNum, pageSize);
  List<User> userList = userRepository.findUsersByUsername(username);
  int count = userRepository.getCount();
  Map<String, Object> tableData = new HashMap<>();
  tableData.put("list", userList);
  tableData.put("count", count);
  return tableData;
 } catch (Exception e) {
  e.printStackTrace();
 }
 return null;
 }
}
public interface UserService {
 Map<String, Object> getTableData(int pageNum, int pageSize, String username);
}

controller文件

@RestController
public class UserController {
 @Autowired
 private UserService userService;
 @GetMapping("getTableData")
 public Map<String, Object> getTableData(int pageNum, int pageSize, String username) {
 try {
  return userService.getTableData(pageNum, pageSize, username);
 } catch (Exception e) {
  e.printStackTrace();
 }
 return null;
 }
}

实体类

public class User {
 private Integer userId;
 private String username;
 private Byte sex;
 private Date createTime;
 public Integer getUserId() {
 return userId;
 }
 public void setUserId(Integer userId) {
 this.userId = userId;
 }
 public String getUsername() {
 return username;
 }
 public void setUsername(String username) {
 this.username = username;
 }
 public Byte getSex() {
 return sex;
 }
 public void setSex(Byte sex) {
 this.sex = sex;
 }
 public Date getCreateTime() {
 return createTime;
 }
 public void setCreateTime(Date createTime) {
 this.createTime = createTime;
 }
}

sql

CREATE TABLE `t_user` (
 `user_id` int(11) NOT NULL AUTO_INCREMENT,
 `username` varchar(32) DEFAULT NULL,
 `sex` tinyint(4) DEFAULT NULL,
 `create_time` datetime DEFAULT NULL,
 PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10003 DEFAULT CHARSET=utf8

在static目录下新建 index.html文件

<!DOCTYPE html>
<html lang="ZH">
<head>
 <meta charset="UTF-8">
 <title>spring boot + mybatis + vue + elementui</title>
 <link rel="stylesheet" href="//cdn.bootcss.com/element-ui/1.1.2/theme-default/index.css" rel="external nofollow" >
 <script src="//cdn.bootcss.com/vue/2.1.8/vue.min.js"></script>
 <script src="//cdn.bootcss.com/element-ui/1.1.2/index.js"></script>
 <script src="//cdn.bootcss.com/vue-resource/1.0.3/vue-resource.min.js"></script>
</head>
<body>
<div id="vm">
 <el-row :gutter="3" >
 <el-col :span="5">
  <el-input placeholder="输入用户名称查询" v-model="username" icon="search" @change="changeUsername">
  </el-input>
 </el-col>
 </el-row>
 <el-table border fit :data="tableData" highlight-current-row >
 <el-table-column type="index" width="50"></el-table-column>
 <el-table-column prop="username" label="用户名称"></el-table-column>
 <el-table-column prop="sex" label="性别" :formatter="formatSex"></el-table-column>
 <el-table-column prop="createTime.time" label="创建时间" sortable :formatter="formatCreateDate"></el-table-column>
 </el-table>
 <el-col class="toolbar" >
 <el-pagination @current-change="findAll" :current-page="currentPage" :page-size="10"
   layout="total, prev, pager, next, jumper" :total="total" ></el-pagination>
 </el-col>
</div>
</body>
<script>
 Vue.http.options.emulateJSON = true;
 Vue.http.options.emulateHTTP = true;
 var vm = new Vue({
 el: '#vm',
 data: {
  tableData: [],
  currentPage: 1,
  total: 10,
  listLoading: false,
  username: null
 },
 mounted: function () {
  this.findAll();
 },
 methods: {
  findAll: function (currentPage) {
  this.listLoading = true;
  if (!isNaN(currentPage)) {
   this.currentPage = currentPage;
  }
  var params_ = {
   pageNum: this.currentPage,
   pageSize: 10
  };
  if (this.username && this.username.trim() != "") {
   params_['username'] = this.username;
  }
  this.$http.get("/getTableData", {
   params: params_
  }).then(function (response) {
   console.log(response.data);
   this.total = response.data.count;
   this.tableData = [];
   for (var key in response.data.list) {
   this.$set(this.tableData, key, response.data.list[key]);
   }
  }).catch(function (response) {
   console.error(response);
  });
  this.listLoading = false;
  },
  formatDate: function getNowFormatDate(time) {
  var date = new Date(time);
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
   month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
   strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
   + " " + date.getHours() + seperator2 + date.getMinutes()
   + seperator2 + date.getSeconds();
  return currentdate;
  },
  formatCreateDate: function (row, column) {
  if (row.createTime != null) {
   return this.formatDate(row.createTime);
  } else {
   return '';
  }
  },
  formatSex: function (row, column) {
  if (row.sex != null) {
   return row.sex == 1 &#63; '男' : '女';
  }
  },
  changeUsername: function () {
  this.findAll(1);
  }
 }
 });
</script>
</html>

启动文件

@EnableAutoConfiguration
@Configuration
@ComponentScan
@MapperScan("com.imooc.repository")
@SpringBootApplication
public class DemoApplication {
 public static void main(String[] args) {
 SpringApplication.run(DemoApplication.class, args);
 }
}

启动项目,打开http://localhost:8080/index.html

在Spring boot项目中使用 mybatis 与Vue实现对数据进行增删改查操作

关于在Spring boot项目中使用 mybatis 与Vue实现对数据进行增删改查操作问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. spring-boot-plus是易于使用,快速,高效,功能丰富,开源的spring boot 脚手
  2. 基于Spring Boot+Spring Security+JWT+Vue前后端分离的开源项目

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue spring boot mybatis

上一篇:Android应用中出现软键盘遮挡住按钮如何解决

下一篇:Trim标签在Mybatis中的使用方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》