MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。由于使用方便,效率高等特性,Mybatis成为实际开发中最常用的ORM框架之一。本文将简单介绍一下Spring Boot + Mybatis实现数据库的增删该查操作。
| pom.xml
| springboot-05-mybatis-curd.iml
|
+---src
| +---main
| | +---java
| | | \---com
| | | \---zhuoli
| | | \---service
| | | \---springboot
| | | \---mybatis
| | | \---curd
| | | | SpringBootMybatisCurdApplicationContext.java
| | | |
| | | +---controller
| | | | UserController.java
| | | |
| | | +---repository
| | | | +---conf
| | | | | DataSourceConfig.java
| | | | |
| | | | +---mapper
| | | | | UserMapper.java
| | | | |
| | | | +---model
| | | | | User.java
| | | | |
| | | | \---service
| | | | | UserRepository.java
| | | | |
| | | | \---impl
| | | | UserRepositoryImpl.java
| | | |
| | | \---service
| | | | UserControllerService.java
| | | |
| | | \---impl
| | | UserControllerServiceImpl.java
| | |
| | \---resources
| | | application.properties
| | |
| | \---base
| | \---com
| | \---zhuoli
| | \---service
| | \---springboot
| | \---mybatis
| | \---curd
| | \---repository
| | \---mapper
| | UserMapper.xml
| |
| \---test
| \---java
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户编号',
`user_name` varchar(25) DEFAULT NULL COMMENT '用户名称',
`description` varchar(25) DEFAULT NULL COMMENT '描述',
`is_deleted` tinyint(3) DEFAULT NULL COMMENT '是否删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
4.0.0
com.zhuoli.service
springboot-05-mybatis-curd
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
mysql
mysql-connector-java
org.projectlombok
lombok
1.18.2
provided
##数据源配置
test.datasource.url=jdbc:mysql://115.47.149.48:3306/zhuoli_test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
test.datasource.username=zhuoli
test.datasource.password=zhuoli
test.datasource.driverClassName=com.mysql.jdbc.Driver
比较一下上节使用jdbcTemplate可以发现,上节application.properties配置都是spring打头的。区别在于本节test打头的propertity是不能被Spring Boot识别并进行数据源默认配置的,相应的本节将使用Java Config的方式进行手动配置(就是手动配置dataSource、transactionManager、sqlSessionFactory),就是接下来将提到的DataSourceConfig。
controller层和service层跟上节使用jdbcTemplate相同,这里具体讲一下使用Mybatis进行crud操作的实现。
@Configuration
public class DataSourceConfig {
@Value("${test.datasource.url}")
private String url;
@Value("${test.datasource.username}")
private String user;
@Value("${test.datasource.password}")
private String password;
@Value("${test.datasource.driverClassName}")
private String driverClass;
@Bean(name = "dataSource")
public DataSource dataSource() {
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "transactionManager")
public DataSourceTransactionManager dataSourceTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
/*设置mapper文件位置*/
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:base/com/zhuoli/service/springboot/mybatis/curd/repository/mapper/*.xml"));
/*设置实体类映射规则: 下划线 -> 驼峰*/
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
sessionFactory.setConfiguration(configuration);
return sessionFactory.getObject();
}
}
@Getter
@Setter
public class User {
private Long id;
private String userName;
private String description;
private Integer isDeleted;
}
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
List findById(@Param("id") Long id);
@Select("SELECT * FROM user")
List getAllUsers();
int createUser(User user);
@Insert("INSERT INTO user(user_name,description, is_deleted) VALUES (#{userName},#{description},0)")
int createUseByAnnotation(User user);
/*软删除*/
@Update("UPDATE user SET is_deleted = 1 WHERE id = #{id}")
int deleteUserById(@Param("id") Long id);
/*彻底删除*/
@Delete("DELETE from user WHERE id = #{id}")
int deleteUserComplete(@Param("id") Long id);
int updateUser(User user);
}
Mapper类用来提供sql查询,从上述Mapper类可以看出,Mapper方法实现分为两种,一种是使用注解(@Select、@Update、@Insert、@Delete),另一种是使用**Mapper.xml中定义sql语句。
INSERT INTO user(user_name,description, is_deleted) VALUES (#{userName},#{description},0)
update user set user_name=#{userName},description=#{description} where id=#{id}
UserMapper.xml定义在resources/base/com/zhuoli/service/springboot/mybatis/curd/repository/mapper/文件夹下,之所以没有将xml文件定义在src/main/java中,是因为src/main/java文件夹下的xml文件不会被编译到classes目标目录。
如果执意要将xml文件定义在src/main/java下,要在pom.xml添加过滤器,将src/main/java下的xml文件编译到classes目标目录,如下:
src/main/resources
src/main/java
**/*.xml
true
关于resource配置原理,参考这篇文章maven的resources介绍
使用postman进行接口测试,由于controller方法参数使用的是@RequestParam接收的,所以测试时,请求头要设置为x-www-form-urlencoded,否则会报“HTTP Status 400 – Required String parameter ‘xx’ is not present”错,具体请查看
通过上述示例,可以看出Mybatis的优缺点:
优点:
缺点:
其实,实际开发中,往往可以通过Mybatis Generator插件,自动生成Model、Example、Mapper、Mapper.xml文件,做到完全不用手写sql,我会在接下来的文章讲解。
示例代码:码云 – 卓立 – Spring Boot + Mybatis CRUD操作