继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Spring boot + mybatis + Vue.js + ElementUI 实现数据的增删改查(2)

努力是为自己将来铺路
关注TA
已关注
手记 10
粉丝 45
获赞 237

继续上一章的,接下来我们添加分页相关的依赖,时间紧张,直接上代码了,贴上我的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?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">
    <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" style="margin: 10px 0;">
        <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 style="width: 100%;font-size: 12px;">
        <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" style="padding:10px;">
        <el-pagination @current-change="findAll" :current-page="currentPage" :page-size="10"
                       layout="total, prev, pager, next, jumper" :total="total" style="float:right"></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 ? '男' : '女';
                }
            },
            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
图片描述

打开App,阅读手记
19人推荐
发表评论
随时随地看视频慕课网APP

热门评论

你都不写mapper.xml都能出来也算厉害的了

UserService 接口的代码好像美方上来?

怎么感觉没用到UserMapper啊,直接用了userRepository

查看全部评论