SpringBoot整合Mybatis
注意
这里的配置文件是properties,一般是yml文件,但是写法都是差不多的
1.1 SpringBoot整合Mybatis
1.1.1 添加Mybatis的起步依赖
<!--mybatis起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
1.1.2 添加数据库驱动坐标
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
1.1.3 添加数据库连接信息
在application.properties中添加数据量的连接信息
#数据库连接信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://dbnode01:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=passw0rd
1.1.4 创建user表
/*Table structure for table `user` */
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) DEFAULT NULL,
`password` VARCHAR(50) DEFAULT NULL,
`name` VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*Data for the table `user` */
INSERT INTO `user`(`id`,`username`,`password`,`name`) VALUES (1,'zhangsan','123','张三');
INSERT INTO `user`(`id`,`username`,`password`,`name`) VALUES (2,'lisi','123','李四');
1.1.5 创建实体Bean
public class User {
private Integer id;//主键
private String username;//用户名
private String password;//密码
private String name;//姓名
//此处省略getter和setter方法 .. ..
}
1.1.6 编写Mapper
@Mapper
public interface UserMapper {
public List<User> queryUserList();
}
注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中
1.1.7 配置Mapper映射文件
在src\main\resources\mapper路径下加入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.itheima.mapper.UserMapper">
<select id="queryUserList" resultType="user">
select * from user
</select>
</mapper>
1.1.8 在application.properties中添加mybatis的信息
#spring集成Mybatis环境
#pojo别名扫描包
mybatis.type-aliases-package=com.itheima.domain
#加载Mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
1.1.9 编写测试Controller
@Controller
public class MybatisController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/query")
@ResponseBody
public List<User> queryUserList(){
List<User> users = userMapper.queryUserList();
return users;
}
}