前言
这是我学习 Spring Boot 的第三篇文章,终于可以见到效果了。错过的同学可以看看之前的文章
我们为什么要学习 Spring Boot
Spring Boot 入门详细分析
在入门的基础上,我们现在已经能运行起来项目了,至少保证 Hello World 是正常的,下面直接进入正题。
准备数据库环境
创建表
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`name` varchar(50) DEFAULT NULL COMMENT '姓名',
`age` int(2) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
工程相关
项目目录结构
编辑配置文件 application.properties 、pom.xml
编辑 application.properties 文件
## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_test?useUnicode=true&characterEncoding=utf8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root ## Mybatis 配置
# 配置为 com.kris.entry 指向实体类包路径。
mybatis.typeAliasesPackage=com.kris.entry
编辑 pom.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.kris</groupId>
<artifactId>demo2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo2</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
<!-- 这个 mybatis 的版本不能太低,否则有问题,无法导入相关注解 -->
<mybatis-spring-boot>1.3.2</mybatis-spring-boot>
<mysql-connector>5.1.39</mysql-connector>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot}</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector}</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
编写实体类
package com.kris.entry; /**
* Created by Kris on 2019/3/20.
*/
public class User { private Integer id; private String name; private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
编写 DAO 接口
package com.kris.dao; import com.kris.entry.User;
import org.apache.ibatis.annotations.*; /**
* Created by Kris on 2019/3/20.
*/
@Mapper
public interface UserDao { /**
* 新增用户
* @param user
*/
@Insert("insert into t_user(id,name,age) values (#{id},#{name},#{age})")
boolean add(User user); /**
* 删除用户
* @param id
*/
@Delete("delete from t_user where id = #{id} ")
boolean delete(Integer id); /**
* 根据用户 ID 修改用户
* @param user
*/
@Update("update t_user set name = #{name},age = #{age} where id = #{id} ")
boolean update(User user); /**
* 根据 ID 查找用户
* @param id
* @return
*/
@Select("select * from t_user where id = #{id}")
User select(Integer id);
}
@Mapper 的作用:实话说,都说有作用,但是我测试了一波,去掉这个也没有问题。谁知道 @Mapper 的作用,麻烦告诉我一声!
@Insert @Delete @Update @Select 对应数据库的增删改查操作。
另外,在绑定参数的过程中,因为只有一个参数,所以可以自动绑定,若是有多个参数,那就需要@Param("XXX") 与 SQL 语句中的参数绑定了。例如:
@Update("update t_user set name = #{name},age = #{age} where id = #{id} ")
boolean update(@Param("name")String name,@Param("age")Integer age,@Param("id")Integer id);
编写 Service 接口以及 Service 实现
这个模块和之前的 SSM 项目没有区别,当前就这个 Demo 来说,也可以不写这个层。
package com.kris.service; import com.kris.entry.User; /**
* Created by Kris on 2019/3/20.
*/
public interface UserService { boolean add(User user); boolean delete(Integer id); boolean update(User user); User select(Integer id);
}
package com.kris.service.impl; import com.kris.dao.UserDao;
import com.kris.entry.User;
import com.kris.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* Created by Kris on 2019/3/20.
*/
@Service
public class UserServiceImpl implements UserService{ @Autowired
UserDao userDao; @Override
public boolean add(User user) {
return userDao.add(user);
} @Override
public boolean delete(Integer id) {
return userDao.delete(id);
} @Override
public boolean update(User user) {
return userDao.update(user);
} @Override
public User select(Integer id) {
return userDao.select(id);
}
}
编写 Controller 层
package com.kris.controller; import com.kris.entry.User;
import com.kris.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; /**
* Created by Kris on 2019/3/20.
*/
@RestController
@RequestMapping("/user")
public class UserController { @Autowired
private UserService userService; @RequestMapping(value = "/add",method = RequestMethod.POST)
public boolean addUser(User user){
return userService.add(user);
} @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
public boolean deleteUser(Integer id){
return userService.delete(id);
} @RequestMapping(value = "/update",method = RequestMethod.PUT)
public boolean updateUser(User user){
return userService.update(user);
} @RequestMapping(value = "/select",method = RequestMethod.GET)
public User selectUser(Integer id){
return userService.select(id);
}
}
@RestController 这个注解等于 @Controller + @ResponseBody 访问结果以 JSON 格式返回,其它的都是以前的知识。
运行项目
package com.kris; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("com.kris.dao")
public class Demo2Application { public static void main(String[] args) {
SpringApplication.run(Demo2Application.class, args);
}
}
SpringBootApplication:开启组件扫描和自动配置。
到这里知道了为什么会有 @Mapper 这个注解了,在之前我们想要实现 Dao 层的实现,我们使用 Mapper 动态代理开发机制,但是外在表现就是在 DAO 接口上添加 @Mapper 即可。但是这样我们需要为每一个 Dao 文件添加注解,太麻烦,现在为了方便,简化操作我们可以直接使用 @MapperScan 进行扫描即可。另外,@MapperScan 这个注解还可以同时扫描多个文件,中间用逗号隔开。我们可以这样写
@MapperScan("com.kris.dao","com.yu.mapper")
测试
测试这里我使用的 Postman ,当然你也可以使用 Restlet 。呃呃,测试就自己来吧,我就不截图了。实在不行,你就用浏览器直接访问啊,但是注意设置请求的形式呦。