一、创建spring项目
1.1 新建项目
1.2 选择依赖
1.3 进入项目
二、配置项目
2.1 添加项目依赖
可先删除不想要的依赖,如下图
然后添加自己的依赖信息
<dependencies>
<!-- 下面是添加的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
可以在maven选项卡查看已经加载的依赖
2.2 配置应用属性
# 应用名称
spring.application.name=spring-demo
# 数据库
spring.datasource.url=jdbc:mysql://localhost:3307/sales
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# mybatis
mybatis.configuration.map-underscore-to-camel-case=true
也可以使用yaml
文件,将properties
后缀改为yml
即可。
三、业务开发
3.1 创建实体类
查看数据库表各字段类型
编写DO实体类
我们可以在创建完所有字段后,使用IDEA
快捷生成getter
和setter
,
也可以使用lombok
提供的@Data
注解自动生成,
上述截图使用了后者的方法。
3.2 编写mapper接口
package com.example.springdemo.mapper;
import com.example.springdemo.pojo.CustomerDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface CustomerMapper {
@Select("SELECT * FROM `customer` limit 50")
List<CustomerDO> selectTop50();
}
3.3 编写service服务层接口和其Impl实现类
package com.example.springdemo.service;
import com.example.springdemo.pojo.CustomerDO;
import java.util.List;
public interface CustomerService {
List<CustomerDO> queryTop50();
}
package com.example.springdemo.service.impl;
import com.example.springdemo.mapper.CustomerMapper;
import com.example.springdemo.pojo.CustomerDO;
import com.example.springdemo.service.CustomerService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class CustomerServiceImpl implements CustomerService {
@Resource
private CustomerMapper customerMapper;
@Override
public List<CustomerDO> queryTop50() {
return customerMapper.selectTop50();
}
}
3.4 编写controller控制层
package com.example.springdemo.controller;
import com.example.springdemo.pojo.CustomerDO;
import com.example.springdemo.service.CustomerService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("customer")
public class CustomerController {
@Resource
private CustomerService customerService;
@GetMapping("list")
public List<CustomerDO> listTop50() {
return customerService.queryTop50();
}
}