提供根据id查询用户信息
的服务
使用Spring Initializr 创建工程
借助于Spring提供的Spring Initializr快速搭建项目:
【next】> 填写模块信息
【next】> 添加项目依赖,选择SpringBoot版本。
【next】> 填写模块位置
修改pom.xml
在<properties>
标签中修改springcloud版本
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
添加通用mapper依赖
<!--通用mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
添加依赖版本统一管理
<!--统一管理依赖的版本号-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
覆盖配置
修改applciation.properties为yml文件
server:
port: 9091
servlet:
context-path: /
mybatis:
type-aliases-package: com.cncs.pojo
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
编写代码
项目目录结构
定义User类
@Data
@Table(name = "user") //表名
public class User implements Serializable {
@Id
//@KeySql(useGeneratedKeys = true) //主键回显,标识主键自增
@GeneratedValue(generator = "JDBC")
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
@Transient//瞬时的,不会被持久化到数据库
private String note; //备注
}
定义UserMapper接口
public interface UserMapper extends Mapper<User> {
}
定义UserService
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User queryById(Integer id){
return userMapper.selectByPrimaryKey(id);
}
}
定义UserController
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("{id}")
public User findById(@PathVariable("id")Integer id){
User user = userService.queryById(id);
return user;
}
}
为springboot引导类添加Mapper接口扫描注解
@MapperScan("com.cncs.mapper")
测试
启动项目,访问接口
附言
PS1:有多个SpringBoot项目,如何在面板上启动工程?
在idea2020.1上没有了springboot dashboard,取而代之的是services面板,它和dashboard作用一样,都是统一管理springboot项目,如何打开services面板呢?
(1)打开idea2020.1 > 【view】>【Tool Windows】>【Services】
(2)在【Services】面板上,点击【Add Service】,然后选择【Spring Boot】