近期朋友有简单的 web 开发需求,半学半做地采用前后端分离的方式,快速学习并搭建了一个网站,前端使用的技术是 boostrap 和 jquery,后端使用的技术是 SpringBoot+Mybatis,数据库采用的是 mysql,在此将后端的搭建过程记录下来并创建了一个 git 项目。该项目可以当做一个脚手架,以后需要搭建 web 项目的时候可以直接使用,只需要更改业务逻辑,不需要再进行复杂的配置。
具体流程
1、新建 Project,选择使用 Spring Initializr 进行项目构建。(Spring 版本为 2.3.0)
2、填写 group 和项目名称。
3、选择依赖,创建的是 maven 工程,会在 pom 文件中生成对应的依赖。我们可以勾选 SpringWeb、JDBC 和 MyBatis。
4、生成项目,项目的文件结构如下。
5、创建 HelloController.java,具体代码如下。
@RestController @RequestMapping(value = "/") public class HelloController { @RequestMapping("hello") public String login(){ return "hello world!!"; } }
复制代码
此时直接运行可能会出现如下错误:
Description: Failed to configure a DataSource: ‘url’ attribute is notspecified and no embedded datasource could be configured.
我们可以对 Application 类的 @SpringBootApplication 注解增加(exclude={DataSourceAutoConfiguration.class}),使得它自动配置数据源,避免该错误。
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})public class SsmDemoApplication {
public static void main(String[] args) { SpringApplication.run(SsmDemoApplication.class, args); }
}
复制代码
6、此时启动 Application,在浏览器中输入 http://localhost:8080/hello 即可。
7、以上过程能够成功执行,但是不包含数据库连接部分,通过以下若干代码和配置的编写,能够实现读取数据库的功能。首先需要创建数据库:
SET FOREIGN_KEY_CHECKS=0;
-- ------------------------------ Table structure for `user`-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `age` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', '张三', '男', '16');INSERT INTO `user` VALUES ('2', '李四', '男', '24');INSERT INTO `user` VALUES ('3', '李静', '女', '18');
复制代码
8、mybatis 中有两种开发方式,一种 dao 开发方式,一种 mapper 开发方式,我们使用 mapper 的方式进行开发。在工程下创建 controller、entity、mapper 和 service 文件夹,并编写相关的代码,实现数据库的读取。controller 用于访问控制,entity 存储 java bean,mapper 用作数据层和业务层的映射,service 用于和数据库交互,出于解耦的考虑,我们使用接口的方式进行编程,因此还有一层 impl 实现层。
User.java
public class User {
private int id; private String name; private String sex; private String age;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getSex() { return sex; }
public void setSex(String sex) { this.sex = sex; }
public String getAge() { return age; }
public void setAge(String age) { this.age = age; }}
复制代码
UserMapper.java
public interface UserMapper { List<User> getAllUser();}
复制代码
UserService.java
public interface UserService { List<User> getAllUser();}
复制代码
UserServiceImpl.java
@Service(value = "userService")public class UserServiceImpl implements UserService {
@Resource private UserMapper userMapper;
@Override public List<User> getAllUser() { return userMapper.getAllUser(); }}
复制代码
UserController
@Controller@RequestMapping(value = "/user")public class UserController { @Autowired private UserService userService;
@RequestMapping("/getAllUser") @ResponseBody private List<User> getAllUser() { List<User> users = userService.getAllUser(); return users; }}
复制代码
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.hnu.elvis.mapper.UserMapper"> <select id="getAllUser" resultType="com.hnu.elvis.entity.User"> SELECT * FROM user </select></mapper>
复制代码
SsmDemoApplication 需要进行修改,如下所示:
@SpringBootApplication@EnableTransactionManagement //开启事务管理@MapperScan("com.hnu.elvis.mapper")//与dao层的@Mapper二选一,会将包中接口都注解成Mapper。public class SsmDemoApplication {
public static void main(String[] args) { SpringApplication.run(SsmDemoApplication.class, args); }
}
复制代码
需要将 application.xml 删除并创建 application.yml,demo 配置如下:
#默认使用配置spring: profiles: active: dev
#公共配置与profiles选择无关mybatis: typeAliasesPackage: com.hnu.elvis.entity mapperLocations: classpath:mapper/*.xml
---
#开发配置spring: profiles: dev
datasource: url: jdbc:mysql://localhost:3306/jewels?serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver
复制代码
9、启动 application 并使用浏览器访问:http://localhost:8080/user/getAllUser
评论