前言
mybatis是一个半自动化的orm框架,所谓半自动化就是mybaitis只支持数据库查出的数据映射到pojo类上,而实体到数据库的映射需要自己编写sql语句实现,相较于hibernate这种完全自动化的框架我更喜欢mybatis,mybatis非常灵活,可以随心所欲的编写自己的sql语句来实现复杂的数据库操作,还会有一种畅酣淋漓的编写sql语句的潇洒感,但是以前的mybaits需要一大堆的配置文件,以及各种mapper和dao和实体的关联,导致使用mybatis还是不够简洁,后来mybatis也发现了这个弊端,开发了mybatis generator工具来自动化生成实体类、mapper配置文件、dao层代码来减轻开发工作量,在后期也是实现了抛弃mapper配置文件基于注解的开发模式,直到现在,mybatis看spring boot这么火热,也开发了一套基于spring boot的模式:mybatis-spring-boot-starter。
spring boot简约轻巧的风格正在逐渐被越来越多的厂商及开发者所认可,包括阿里的开源RPC框架dubbo也准备开发一套对spring boot应用的支持(dubbo-spring-boot-starter启动配置模块)
正文
springboot与mybatis集成
首先还是从http://start.spring.io/ 上初始化一个项目下来,然后在pom.xml文件中加入mybatis启动项(由于mybatis-spring-boot-starter依赖了spring-boot-starter,所以可以不用再添加spring-boot-starter了)以及mysql及web依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
在application.properties中配置数据源及mybatis配置:
spring.application.name=spring-boot-config
server.port=8080
server.context-path=/
#mybatis.config-location=classpath:mybatis-config.xml
#mybatis mapper文件的位置
mybatis.mapper-locations=classpath*:mapper/**/*.xml
#扫描pojo类的位置,在此处指明扫描实体类的包,在mapper中就可以不用写pojo类的全路径名了
mybatis.type-aliases-package=com.cuit
jdbc.type=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
可以通过mybatis.config-location属性来指定mybatis的配置文件的位置,简单起见这里使用默认配置就不用指定了,接下来分别在数据库中创建user表,并插入一些数据
分别创建pojo类和dao接口对应mapper文件
public class User{
private String id;
private String name;
private String sex;
private int age;
}
@Mapper//加上该注解才能使用@MapperScan扫描到
public interface UserDao {
User getUs