MyBatis 是一款优秀的持久层框架,支持定制化 SQL、存储过程以及高级映射。它采用面向对象编程的方式对数据库进行 CRUD 的操作,使程序中对关系数据库的操作更方便简单。它支持 XML 描述符配置文件和注解两种方式执行 SQL 语句。“简单灵活”是它在对象关系映射工具上的最大优势。
过去使用 MyBatis 开发,需要各种配置文件、实体类、Dao 层映射关联、还有一大推其它配置。经过进行不断的优化后,终于他来了, mybatis-spring-boot-starter
可以做到无需配置只用注解开发,也可以使用简单的配置轻松上手。
当然两种方式都需要在 POM 文件引入 mybatis-spring-boot-starter
:
<!-- mybaits --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> 复制代码
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for t_user -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` int(8) NOT NULL AUTO_INCREMENT COMMENT 'ID', `user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户姓名', `user_sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户性别', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_user -- ---------------------------- BEGIN; INSERT INTO `t_user` VALUES (1, '刘备', '男'); INSERT INTO `t_user` VALUES (2, '孙尚香', '女'); INSERT INTO `t_user` VALUES (3, '周瑜', '男'); INSERT INTO `t_user` VALUES (4, '小乔', '女'); INSERT INTO `t_user` VALUES (5, '诸葛亮', '男'); INSERT INTO `t_user` VALUES (6, '黄月英', '女'); INSERT INTO `t_user` VALUES (7, '关羽', '男'); INSERT INTO `t_user` VALUES (8, '张飞', '男'); INSERT INTO `t_user` VALUES (9, '赵云', '男'); INSERT INTO `t_user` VALUES (10, '黄总', '男'); INSERT INTO `t_user` VALUES (11, '曹操', '男'); INSERT INTO `t_user` VALUES (12, '司马懿', '男'); INSERT INTO `t_user` VALUES (13, '貂蝉', '女'); INSERT INTO `t_user` VALUES (14, '吕布', '男'); INSERT INTO `t_user` VALUES (15, '马超', '男'); INSERT INTO `t_user` VALUES (16, '魏延', '男'); INSERT INTO `t_user` VALUES (17, '孟获', '男'); INSERT INTO `t_user` VALUES (18, '大乔', '女'); INSERT INTO `t_user` VALUES (19, '刘婵', '男'); INSERT INTO `t_user` VALUES (20, '姜维', '男'); INSERT INTO `t_user` VALUES (21, '廖化', '男'); INSERT INTO `t_user` VALUES (22, '关平', '男'); COMMIT; SET FOREIGN_KEY_CHECKS = 1; 复制代码
public class UserEntity { private Long id; private String userName; private String userSex; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } } 复制代码
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- 热部署模块 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <!-- 这个需要为 true 热部署才有效 --> </dependency> <!-- mysql 数据库驱动. --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- mybaits --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> </dependencies> 复制代码
#datasource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=true spring.datasource.username=root spring.datasource.password=root 复制代码
在启动类中添加对 mapper 包扫描@MapperScan
@SpringBootApplication @MapperScan("cn.zwqh.springboot.dao") public class SpringBootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMybatisApplication.class, args); } } 复制代码
或者直接在 Mapper 类上面添加注解@Mapper,建议使用上面那种,不然每个 mapper 加个注解也挺麻烦的
public interface UserDao { //使用注解方式 /** * 获取所有用户 * @return */ @Select("select * from t_user") @Results({ @Result(property = "userName",column = "user_name"), @Result(property = "userSex",column = "user_sex") }) List<UserEntity> getAll2(); /** * 根据id获取用户 * @param id * @return */ @Select("select * from t_user where id=#{id}") @Results({ @Result(property = "userName",column = "user_name"), @Result(property = "userSex",column = "user_sex") }) List<UserEntity> getOne2(Long id); /** * 新增用户 * @param user */ @Insert("insert into t_user (user_name,user_sex) values(#{userName},#{userSex})") void insertUser2(UserEntity user); /** * 修改用户 * @param user */ @Update("update t_user set user_name=#{userName},user_sex=#{userSex} where id=#{id}") void updateUser2(UserEntity user); /** * 删除用户 * @param id */ @Delete("delete from t_user where id=#{id}") void deleteUser2(Long id); } 复制代码
注解: @Select 是查询类的注解,所有的查询均使用这个 @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。 @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值 @Update 负责修改,也可以直接传入对象 @delete 负责删除
UserController
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserDao userDao; //使用注解方式 /** * 获取所有用户 * @return */ @RequestMapping("/getAll2") public List<UserEntity> getAll2(){ return userDao.getAll2(); } /** * 根据id获取用户 * @return */ @RequestMapping("/getOne2") public List<UserEntity> getOne2(Long id){ return userDao.getOne2(id); } /** * 新增用户 * @param user * @return */ @RequestMapping("/insertUser2") public String insertUser2(UserEntity user) { userDao.insertUser2(user); return "insert success"; } /** * 修改用户 * @param user * @return */ @RequestMapping("/updateUser2") public String updateUser2(UserEntity user) { userDao.updateUser2(user); return "update success"; } /** * 删除用户 * @param user * @return */ @RequestMapping("/deleteUser2") public String deleteUser2(Long id) { userDao.deleteUser2(id); return "delete success"; } } 复制代码
启动项目后可以通过浏览器访问 http://127.0.0.1:8080/user/getOne2?id=1
进行测试,其他雷同。也可以编写单元测试进行测试。
#datasource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=true spring.datasource.username=root spring.datasource.password=root #mybatis mybatis.mapper-locations=classpath:/mapper/*.xml 复制代码
public interface UserDao { //mapper.xml方式 /** * 获取所有用户 * @return */ List<UserEntity> getAll(); /** * 根据id获取用户 * @return */ List<UserEntity> getOne(Long id); /** * 新增用户 * @param user */ void insertUser(UserEntity user); /** * 修改用户 * @param user */ void updateUser(UserEntity user); /** * 删除用户 * @param id */ void deleteUser(Long id); } 复制代码
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.zwqh.springboot.dao.UserDao"> <resultMap type="cn.zwqh.springboot.model.UserEntity" id="user"> <id property="id" column="id"/> <result property="userName" column="user_name"/> <result property="userSex" column="user_sex"/> </resultMap> <!-- 获取所有用户 --> <select id="getAll" resultMap="user"> select * from t_user </select> <!-- 根据用户ID获取用户 --> <select id="getOne" resultMap="user"> select * from t_user where id=#{id} </select> <!-- 新增用户 --> <insert id="insertUser" parameterType="cn.zwqh.springboot.model.UserEntity"> insert into t_user (user_name,user_sex) values(#{userName},#{userSex}) </insert> <!-- 修改用户 --> <update id="updateUser" parameterType="cn.zwqh.springboot.model.UserEntity"> update t_user set user_name=#{userName},user_sex=#{userSex} where id=#{id} </update> <!-- 删除用户 --> <delete id="deleteUser" parameterType="Long"> delete from t_user where id=#{id} </delete> </mapper> 复制代码
个人觉得,注解方式适合轻量级的项目,现在的微服务项目比较适合这种模式;对于大型项目,复杂的多表联合查询sql用 xml 更适合。
<!-- pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.12</version> </dependency> 复制代码
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserDao userDao; /** * 使用pagehelper分页插件 * @param pageNum * @param pageSize * @return */ @RequestMapping("/pagehelperTest") public List<UserEntity> pagehelperTest(int pageNum,int pageSize){ PageHelper.startPage(pageNum, pageSize); return userDao.getAll(); //直接使用上面的 mapper } } 复制代码
浏览器直接访问 http://127.0.0.1:8080/user/pagehelperTest?pageNum=1&pageSize=10
,改变参数试试。