1

事情呢是这样的,此前我们公司内部用python的flask框架和vue全家桶做了一个内部管理系统,感觉效果还不错,然后就打算用spring boot再实现个类似的系统以支持公司业务,所以最近就捣鼓了下spring boot,之前没接触过这个框架,感觉挺高大上的,网上炒得也很火热,所以我打算写一篇关于对spring boot初体验文章以记录我使用这个框架受到的冲击,因为这个框架确实太好用了,不禁再来感叹一下,牛掰class。好了,话不多说,开搞~

如何获取框架

spring boot官方提供了一个Spring Initializr,这玩意儿是Spring Boot应用的一个简单脚手架工具。就是通过页面上的操作,很快帮你生成搭建好一个初始化好的Spring Boot应用。
传送门:https://start.spring.io/
打开上面链接,可以看到一堆可选项,请看下图,基本上按照默认的配置走是完全ojbk的默认配置.png
将代码下载下来之后导入到开发工具中,我用的是eclipse,前提是要先配置好maven,这里我就不细说maven是如何配置的了。然后maven就开始帮我下载所需jar包,如果网速太慢的话可以将maven下载源配置成阿里的,依赖下载完成之后,我们就算是得到了一个完整的初始版本的spring boot项目了。

hello world from spring boot

我们的目标是做一个web项目,那么我们就要加入相关依赖

<!-- web启动器依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

添加完web启动依赖之后就可以去写一个HelloWorldController了

package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
    @GetMapping("/helloWorld")
    public String helloWorld() {
        return "hello world from spring boot";
    }
}

选中DemoApplication.java,右键选择Run As -> Java Application,因为spring boot内置了tomcat,所以也不需要配置外部tomcat,直接就欢快的运行起来了,启动完项目后,浏览器访问http://localhost:8080/helloWorld,就可以看到返回的hello world from spring boot。

spring boot整合mybatis

我们最想知道的,可能就是如何通过spring boot去访问数据库,然后给前端返回json数据。
下面我们就来看如何整合mybatis
首先,还要添加与mybatis相关的依赖

<!-- 整合Mybatis -->
<!-- Mybatis启动器 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>
<!-- JDBC启动器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>
<!-- druid数据库连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.20</version>
</dependency>

然后我们还需要在src/main/resources目录下的配置文件application.properties中添加相关配置:连接数据库信息、数据库驱动、数据库账号和密码、数据库连接池类型

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

当然,数据库你们自己去建吧,把test改成你们自己的,然后需要建一个user表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `real_name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `password` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dept` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_Index_username` (`user_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

准备工作做完了,现在我们就可以来开始写查询用户的API了

一、 新建User.java实体类

package com.example.demo.pojo;
public class User {
    private Integer id;
    private String userName;
    private String realName;
    private String password;
    private String dept;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getRealName() {
        return realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }
}

二、 新建UserMapper.java接口类

package com.example.demo.mapper;
import java.util.List;
import com.example.demo.pojo.User;
public interface UserMapper {
    //根据用户id查询
    User selectByPrimaryKey(Integer id);
    //查询所有用户
    List<User> selectAll();
}

在com.example.demo.mapper包下再新建一个UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.example.demo.pojo.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="real_name" jdbcType="VARCHAR" property="realName" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="dept" jdbcType="VARCHAR" property="dept" />
  </resultMap>
  <sql id="Base_Column_List">
    id, user_name, real_name, password, dept
  </sql>
  <!-- 根据用户id查询 -->
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <!-- 查询所有用户 -->
  <select id="selectAll" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
  </select>
</mapper>

这里有一点比较重要,在新建完mapper之后,需要在项目启动类DemoApplication中添加扫描mapper的注解,如下

package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.mapper") // 指定扫描接口和映射配置文件
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

如果不添加扫描注解@MapperScan("com.example.demo.mapper"),项目启动的时候找不到mapper下面的java类,就会报错。

三、 有了mapper之后,我们就可以来写service层了
新建UserService.java接口类

package com.example.demo.service;
import java.util.List;
import com.example.demo.pojo.User;
public interface UserService {
    //根据用户id查询
    User getUserById(Integer id);
    //查询所有用户
    List<User> getUserList();
}

新建UserServiceImpl.java实现类去实现UserService.java中的方法

package com.example.demo.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User getUserById(Integer id) {
        return this.userMapper.selectByPrimaryKey(id);
    }
    @Override
    public List<User> getUserList() {
        return this.userMapper.selectAll();
    }
}

四、 最后在controller中就可以调用service中的方法去查询数据了

package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/getUserById")
    public User getUserById(Integer id) {
        return this.userService.getUserById(id);
    }
    @GetMapping("/getUserList")
    public List<User> getUserList() {
        return this.userService.getUserList();
    }
}

五、在浏览器中测试接口
前提是数据库里得有数据才行~要先添加几条测试数据哦
根据id查询用户:http://localhost:8080/user/getUserById?id=2
查询所有用户:http://localhost:8080/user/getUserList
访问以上两个地址,即可在浏览器中显示数据库里的数据

结语

经过以上步骤我们就已经完成了一个非常简单粗暴易上手的spring boot项目了,但是这才刚刚起步,还有很多需要我们去探索的,后续我将逐渐更新我学习spring boot框架的过程,希望对看到这篇文章的朋友有帮助,写了一早上,还可以摸会儿鱼就吃午饭咯~


lyyyyb
1 声望1 粉丝