新建一个Spring Initializr项目,选择依赖项:
还需要添加依赖,mysql jdbc 连接容器 和 Druid 连接池,完整的依赖配置:
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
mysql
mysql-connector-java
runtime
com.alibaba
druid-spring-boot-starter
1.1.10
在主包下面新建四个分包:controller、mapper、entity、service,resource文件夹下新建mapping文件夹。
新建数据表,(为了测试临时建的表,根据实际情况自行对应):
CREATE TABLE `uc_users` (
`uid` bigint(0) NOT NULL AUTO_INCREMENT,
`uname` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`upass` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`real_name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`c_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
`c_user` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`uid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
在entity下新建表对象:
public class User {
private Integer uid ;
private String uname = "" ;
private String upass = "" ;
private String real_name = "";
private String c_time = "";
private String c_user = "";
//get \ set 、 toString
}
在mapper下新建UserMapper:
@Mapper
public interface UserMapper {
User findUser(int id);
}
在services新建UserService
@Service
public class UserService {
@Autowired
UserMapper userMapper ;
public User findUser(int id){
return userMapper.findUser(id);
}
}
在controller下新建UserController
@RestController
public class UserController {
@Autowired
UserService userService ;
@RequestMapping("/user/{id}")
public String findUser(@PathVariable int id){
return userService.findUser(id).toString();
}
}
实现配置文件application.properties:
server.port=6000
#mysql datasource
spring.datasource.url = jdbc:mysql:///mg_server?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = root
#连接池
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
#mybatis
mybatis.mapper-locations = classpath:mapping/*Mapper.xml
mybatis.type-aliases-package = org.mg.uc.center.mapper
在mapping文件夹下新建UserMapper.xml:
namespace : 对应Mapper具体类。
resultType : 对应具体实体类
启动类添加mapper包扫描
@MapperScan("com.study.s0720.demo.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
最终项目结构是这样的:
尝试启动项目,启动成功,浏览器访问:http://localhost:6000/user/1
难得这么顺利的一次成功,学习过程可是很坎坷,毕竟看网上的资料,按照别的步骤,对于新手来说也难免 有各种各样的问题,要不断的去尝试解决,才能搞明白各个细节需要注意的地方。
笔者学习的时候,跟随其他博客内容,无法完全运行起来,会遇到各种问题,为了防止跟笔者一样的问题,这里将代码也一并放上:
https://download.csdn.net/download/ssdate/12642139