為了賬號安全,請及時綁定郵箱和手機立即綁定

Spring boot + mybatis + Vue.js + ElementUI 實現數據的增刪改查(2)

2017.01.05 21:23 31294瀏覽

繼續上一章的,接下來我們添加分頁相關的依賴,時間緊張,直接上代碼了,貼上我的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" >
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="http://cdn.bootcss.com/vue/2.1.8/vue.min.js"></script>
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="http://cdn.bootcss.com/element-ui/1.1.2/index.js"></script>
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="http://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
圖片描述

點擊查看更多內容

本文原創發布于慕課網 ,轉載請注明出處,謝謝合作

19人點贊

若覺得本文不錯,就分享一下吧!

評論

相關文章推薦

正在加載中
意見反饋 幫助中心 APP下載
官方微信

舉報

0/150
提交
取消
lpl竞猜