工具
- Idea
- MySql
- Maven
步骤
一 项目创建
- 创建Springboot项目:
设置成默认值就可以。 - Project信息填写:
Type选择maven,项目名称自己命名就可以,其他选项默认。 - 依赖的选择:
选择Web就可以,SpringBoot的版本使用默认就可以(Maven库上最新稳定版本) - 存储位置的选择:
自己选择存储位置就可以,然后Click Finish就可以了。 - 完成之后项目结构浏览:
二 配置完善项目
-
配置pom.xml文件,添加依赖,主要包括:1、mybatis-spring-boot-starter,2、mysql-connector-java
-
更换配置文件格式,将application.properties改成application.yml,配置相关信息。
-
编写Entity、Mapper、Service、ServiceImpl、Controller。
-
Entity代码
public class Users implements Serializable {
private String id;
private String username;
private String password;
getter and setter 方法自己生成一下就可以
}
- Mapper书写
<!--Mapper.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.demo.springboot.mapper.UsersMapper">
<select id="findAll" resultType="com.demo.springboot.entity.Users">
SELECT id,username,password FROM users
</select>
</mapper>
//Mapper接口
@Mapper
public interface UsersMapper {
public List<Users> findAll();
}
- Service和ServiceIpml的编写
//service
public interface UsersService {
public List<Users> findAll();
}
//Service实现类的编写
@Service
public class UsersServiceImpl implements UsersService {
@Autowired
private UsersMapper usersMapper;
@Override
public List<Users> findAll() {
return usersMapper.findAll();
}
}
- Controller编写
@RestController
public class UsersController {
@Autowired
private UsersService usersService;
@RequestMapping("/findAll")
public List<Users> findAll(){
return usersService.findAll();
}
}
三 项目启动
- 通过SpringApplication启动项目
//外部Tomcat部署需要继承:SpringBootServletInitializer
@SpringBootApplication
public class SpringbootMybatisApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
- 项目访问
可以通过http://localhost:8080/findAll 访问
四 注意事项
- 出现Mapper和Mapper.xml不匹配的情况,是因为Mapper.xml没有被加载进去
修改pom.xml,添加配置文件的过滤:
<build>
<!--自定义war包的名字-->
<finalName>SpringBoot</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<!--过滤配置文件.xml和.properties-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
- 无法注入或者找不到类的情况
查看SpringbootMybatisApplication是不是在使用类的父目录,不然不会扫描子目录的包。 - 如何显示数据库连接不到,查看一下pom.xml的依赖,还有application.yml
- 在编写application.yml的时候,一定要注意缩紧行,还有格式的样子。
五 后续
如果有好的见解或者问题,请留言,如果此文对你有帮助,请点个赞,留个喜欢,谢谢!
Demo的地址:http://download.csdn.net/download/i_kang/10126581