SpringBoot与Mybatis框架的整合
经过前面的讲解,接下来我们要做的是springBoot与Mybatis的整合
要求:
jdk:1.8
开发工具:IDEA
注:本次采用全注解方式进行开发。
1.首先创建springboot项目。
我创建的项目名是SpringBoot-Mybatis-Pro
2.查看pom.xml文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>
大家看这里:我的父依赖版本为2.1.2版本,之前用这个版本创建的整合的项目都无法成功运行。所以,这里将父依赖版本换成了1.5.2版本。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>
3.创建我们的数据库表并插入数据
create tabletb_user
(
id
int(11) not null auto_increment,
username
varchar(50) default null,
adress
varchar(250) default null,
sex
varchar(20) default null,
primary key (id
)
) engine=InnoDB auto_increment=6 default charset=utf8;
4.修改application。properties文件
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/microservice
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
设置的端口号为8080,大家也可以设置为8081。
5.编写项目。首先在com包下创建四个文件夹。
在po包下编写User类
private int id;
private String username;
private String adress;
//getter,setter
注:属性名尽量与数据库中列名相同。
5.2编写Usermapper层
@Mapper
public interface UserMapper {
@Select(“select * from tb_user where id = #{id}”)
User findById(int id);
}
注:Mybatis于Hibernate有一点不同的是:from后面跟的是数据库中的表名,而hibernate的from后面跟的是实体类的名字。
5.3编写service层
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findById(int id) {
System.out.println(id);
return userMapper.findById(id);
}
}
在这里声明UserMapper类的对象会报错,但是不影响项目。可以忽略。其中,@AutoWired的作用:可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。无需再通过传统的在bean的xml文件中进行bean的注入配置。
5.4编写controller层
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findById/{id}")
@ResponseBody
public User findById(@PathVariable int id) {
User user = userService.findById(id);
System.out.println(user);
return user;
}
}
注:@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据,需要注意的呢,在使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
5.5编写Application.java
@SpringBootApplication
@MapperScan(“com.mapper.*”)
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
注:@MapperScan可以指定要扫描的Mapper类的包的路径。也可以使用@MapperScan注解多个包。
6.启动我们的项目。
上图可以看出没有问题。
接下来在浏览器中输入:http:…localhost:8080/findById/1。结果如下:
说明我们的项目整合很完美!注:在运行时,我们的项目可能会报错,不用惊慌,这是我们的端口号被占用了。在任务管理器中去进行管理。其实,在做整合时,我遇到了很多坑,足足用了一个星期才让项目完美运行起来。所以万事开头难啊!如果这篇文章对大家有帮助的话,请大家点赞。后继文章将会很快跟大家见面。谢谢大家!