SpringBoot整合Mybatis
springboots使用的版本是2.0.1,注意不同版本可能有差异,并不一定通用
添加Mybatis的起步依赖:
<!--mybatis起步依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
添加数据库驱动坐标:
<!-- MySQL连接驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
添加数据库连接信息:
在application.properties中添加数据量的连接信息
# 数据库连接信息 spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root
创建user表:
在test数据库中创建user表
-- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `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=10 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (‘1‘, ‘zhangsan‘, ‘123‘, ‘张三‘); INSERT INTO `user` VALUES (‘2‘, ‘lisi‘, ‘123‘, ‘李四‘);
创建实体Bean:
public class User { // 主键 private Long id; // 用户名 private String username; // 密码 private String password; // 姓名 private String name; //此处省略getter和setter方法 .. .. }
编写Mapper:
@Mapper public interface UserMapper { public List<User> queryUserList(); }
注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中
配置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.fgy.mapper.UserMapper"> <select id="queryUserList" resultType="user"> select * from user </select> </mapper>
在application.properties中添加mybatis的信息:
#spring集成Mybatis环境 #pojo别名扫描包 mybatis.type-aliases-package=com.fgy.domain #加载Mybatis映射文件 mybatis.mapper-locations=classpath:mapper/*Mapper.xml
编写测试Controller(因为是演示效果,省略了业务层):
@Controller public class MapperController { @Autowired private UserMapper userMapper; @RequestMapping("/queryUser") @ResponseBody public List<User> queryUser(){ List<User> users = userMapper.queryUserList(); return users; } }
如果是基于注解开发持久层:
在application.properties中去掉 mybatis.mapper-locations=classpath:mapper/*Mapper.xml
在启动主类添加扫描器 @MapperScan("com.fgy.mapper")
在持久层方法上添加SQL语句 @Select("select * from user")
相关推荐
dongxurr 2020-08-08
Dullonjiang 2020-07-30
liqiancao 2020-07-26
helloxusir 2020-07-08
mituan 2020-06-14
xiuyangsong 2020-11-16
Nishinoshou 2020-11-09
jimgreatly 2020-09-01
dongxurr 2020-08-18
Dullonjiang 2020-08-15
Dullonjiang 2020-08-11
Dullonjiang 2020-08-09
yunzhonmghe 2020-08-07
jimgreatly 2020-08-03
jimgreatly 2020-07-27
xiuyangsong 2020-07-26
dongxurr 2020-07-26
mcvsyy 2020-07-26