Spring Boot入门系列(十八)mybatis 使用注解实现增删改查,无需xml文件!
之前介绍了Spring Boot 整合mybatis 使用xml配置的方式实现增删改查,还介绍了自定义mapper 实现复杂多表关联查询。虽然目前 mybatis 使用xml 配置的方式 已经极大减轻了配置的复杂度,支持 generator 插件 根据表结构自动生成实体类、配置文件和dao层代码,减轻很大一部分开发量;但是 java 注解的运用发展到今天。约定取代配置的规范已经深入人心。开发者还是倾向于使用注解解决一切问题,注解版大的特点是具体的 SQL 文件需要写在 Mapper 类中,取消了 Mapper 的 XML 配置 。这样不用任何配置文件,就可以简单配置轻松上手。所以今天就介绍Spring Boot 整合mybatis 使用注解的方式实现数据库操作 。
Spring Boot 整合mybatis 使用xml配置版之前已经介绍过了,不清楚的朋友可以看看之前的文章:《Spring Boot入门系列(十一)如何整合Mybatis,实现增删改查【XML 配置版】》。
一、整合Mybatis
Spring Boot 整合Mybatis 的步骤都是一样的,已经熟悉的同学可以略过。
1、pom.xml增加mybatis相关依赖
我们只需要加上pom.xml文件这些依赖即可。
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.41</version></dependency><!--mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version></dependency><!--mapper--><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>1.2.4</version></dependency><!-- pagehelper --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.3</version></dependency><!-- druid 数据库连接框架--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.9</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.2</version><scope>compile</scope><optional>true</optional></dependency>
2、application.properties配置数据连接
application.properties 中需要增加 mybatis 相关的数据库配置。
############################################################# 数据源相关配置,这里用的是阿里的druid 数据源############################################################spring.datasource.url=jdbc:mysql://localhost:3306/zwz_testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.druid.initial-size=1spring.datasource.druid.min-idle=1spring.datasource.druid.max-active=20spring.datasource.druid.test-on-borrow=truespring.datasource.druid.stat-view-servlet.allow=true############################################################# mybatis 相关配置############################################################mybatis.type-aliases-package=com.weiz.pojomybatis.mapper-locations=classpath:mapper/*.xmlmapper.mappers=com.weiz.utils.MyMapper #这个MyMapper 就是我之前创建的mapper统一接口。后面所有的mapper类都会继承这个接口mapper.not-empty=falsemapper.identity=MYSQL# 分页框架pagehelper.helperDialect=mysqlpagehelper.reasonable=truepagehelper.supportMethodsArguments=truepagehelper.params=count=countSql
这里的配置有点多,不过基本的配置都在这。
3、在启动主类添加扫描器
@SpringBootApplication//扫描 mybatis mapper 包路径@MapperScan(basePackages = "com.weiz.mapper") // 这一步别忘了。//扫描 所有需要的包, 包含一些自用的工具类包 所在的路径@ComponentScan(basePackages = {"com.weiz","org.n3r.idworker"})public class SpringBootStarterApplication {public static void main(String[] args) {SpringApplication.run(SpringBootStarterApplication.class, args);}}
在SpringBootStarterApplication 启动类中增加包扫描器。
注意:这一步别忘了,需要在SpringBootStarterApplication 启动类中增加包扫描器,自动扫描加载com.weiz.mapper 里面的mapper 类。
以上,就把Mybatis 整合到项目中了。 接下来就是创建表和pojo类,mybatis提供了强大的自动生成功能。只需简单几步就能生成pojo 类和mapper。
二、代码自动生成工具
Mybatis 整合完之后,接下来就是创建表和pojo类,mybatis提供了强大的自动生成功能的插件。mybatis generator插件只需简单几步就能生成pojo 类和mapper。操作步骤和xml 配置版也是类似的,要注意的是 generatorConfig.xml 的部分配置,要配置按注解的方式生成mapper 。
1、增加generatorConfig.xml配置文件
在resources 文件下创建 generatorConfig.xml 文件。此配置文件独立于项目,只是给自动生成工具类的配置文件,具体配置如下:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><context id="DB2Tables" targetRuntime="MyBatis3"><commentGenerator><property name="suppressDate" value="true"/><!-- 是否去除自动生成的注释 true:是 :false:否 --><property name="suppressAllComments" value="true"/></commentGenerator><!--数据库链接URL,用户名、密码 --><jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/zwz_test" userId="root" password="root"></jdbcConnection><javaTypeResolver><property name="forceBigDecimals" value="false"/></javaTypeResolver><!-- 生成模型的包名和位置--><javaModelGenerator targetPackage="com.weiz.pojo" targetProject="src/main/java"><property name="enableSubPackages" value="true"/><property name="trimStrings" value="true"/></javaModelGenerator><!-- 生成映射文件的包名和位置--><sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"><property name="enableSubPackages" value="true"/></sqlMapGenerator><!-- 生成DAO的包名和位置--><!-- XMLMAPPER生成xml映射文件, ANNOTATEDMAPPER生成的dao采用注解来写sql --><javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.weiz.mapper" targetProject="src/main/java"><property name="enableSubPackages" value="true"/></javaClientGenerator><!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--><table tableName="sys_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table></context></generatorConfiguration>
注意:
这里的配置 <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.weiz.mapper" targetProject="src/main/java">
type 的值很重要:
XMLMAPPER :表示生成xml映射文件。
ANNOTATEDMAPPER:表示生成的mapper 采用注解来写sql。
2、数据库User表
需要在数据库中创建相应的表。这个表结构很简单,就是普通的用户表sys_user。
CREATE TABLE `sys_user` (`id` varchar(32) NOT NULL DEFAULT '',`username` varchar(32) DEFAULT NULL,`password` varchar(64) DEFAULT NULL,`nickname` varchar(64) DEFAULT NULL,`age` int(11) DEFAULT NULL,`sex` int(11) DEFAULT NULL,`job` int(11) DEFAULT NULL,`face_image` varchar(6000) DEFAULT NULL,`province` varchar(64) DEFAULT NULL,`city` varchar(64) DEFAULT NULL,`district` varchar(64) DEFAULT NULL,`address` varchar(255) DEFAULT NULL,`auth_salt` varchar(64) DEFAULT NULL,`last_login_ip` varchar(64) DEFAULT NULL,`last_login_time` datetime DEFAULT NULL,`is_delete` int(11) DEFAULT NULL,`regist_time` datetime DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
3、创建GeneratorDisplay类
package com.weiz.utils;import java.io.File;import java.util.ArrayList;import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.internal.DefaultShellCallback;public class GeneratorDisplay {public void generator() throws Exception{List<String> warnings = new ArrayList<String>();boolean overwrite = true;//指定 逆向工程配置文件File configFile = new File("generatorConfig.xml");ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(configFile);DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,callback, warnings);myBatisGenerator.generate(null);}public static void main(String[] args) throws Exception {try {GeneratorDisplay generatorSqlmap = new GeneratorDisplay();generatorSqlmap.generator();} catch (Exception e) {e.printStackTrace();}}}
这其实也是调用mybatis generator实现的。跟mybatis generator安装插件是一样的。
注意:利用Generator自动生成代码,对于已经存在的文件会存在覆盖和在原有文件上追加的可能性,不宜多次生成。如需重新生成,需要删除已生成的源文件。
4、Mybatis Generator自动生成pojo和mapper
运行GeneratorDisplay 如下图所示,即可自动生成相关的代码。
上图可以看到,pojo 包里面自动生成了User 实体对象 ,mapper包里面生成了 UserMapper 和UserSqlProvider 类。UserMapper 是所有方法的实现。UserSqlProvider则是为UserMapper 实现动态SQL。
注意:
UserMapper 中的所有的动态SQL脚本,都定义在类UserSqlProvider中。若要增加新的动态SQL,只需在UserSqlProvider中增加相应的方法,然后在UserMapper中增加相应的引用即可,
如:@UpdateProvider(type=UserSqlProvider.class, method="updateByPrimaryKeySelective")。
三、实现增删改查
在项目中整合了Mybatis并通过自动生成工具生成了相关的mapper和配置文件之后,下面就开始项目中的调用。这个和之前的xml 配置版也是一样的。
1、在service包下创建UserService及UserServiceImpl接口实现类
创建com.weiz.service包,添加UserService接口类
package com.weiz.service;import com.weiz.pojo.User;public interface UserService {public int saveUser(User user);public int updateUser(User user);public int deleteUser(String userId);public User queryUserById(String userId);}
创建com.weiz.service.impl包,并增加UserServiceImpl实现类,并实现增删改查的功能,由于这个代码比较简单,这里直接给出完整的代码。
package com.weiz.service.impl;import com.weiz.mapper.UserMapper;import com.weiz.pojo.User;import com.weiz.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic int saveUser(User user) {return userMapper.insertSelective(user);}@Overridepublic int updateUser(User user) {return userMapper.updateByPrimaryKeySelective(user);}@Overridepublic int deleteUser(String userId) {return userMapper.deleteByPrimaryKey(userId);}@Overridepublic User queryUserById(String userId) {return userMapper.selectByPrimaryKey(userId);}}
2、编写controller层,增加MybatisController控制器
package com.weiz.controller;import com.weiz.pojo.User;import com.weiz.utils.JSONResult;import com.weiz.service.UserService;import org.n3r.idworker.Sid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Date;@RestController@RequestMapping("mybatis")public class MyBatisCRUDController {@Autowiredprivate UserService userService;@Autowiredprivate Sid sid;@RequestMapping("/saveUser")public JSONResult saveUser() {String userId = sid.nextShort();User user = new User();user.setId(userId);user.setUsername("spring boot" + new Date());user.setNickname("spring boot" + new Date());user.setPassword("abc123");user.setIsDelete();user.setRegistTime(new Date());userService.saveUser(user);return JSONResult.ok("保存成功");}@RequestMapping("/updateUser")public JSONResult updateUser() {User user = new User();user.setId("10011001");user.setUsername("10011001-updated" + new Date());user.setNickname("10011001-updated" + new Date());user.setPassword("10011001-updated");user.setIsDelete();user.setRegistTime(new Date());userService.updateUser(user);return JSONResult.ok("保存成功");}@RequestMapping("/deleteUser")public JSONResult deleteUser(String userId) {userService.deleteUser(userId);return JSONResult.ok("删除成功");}@RequestMapping("/queryUserById")public JSONResult queryUserById(String userId) {return JSONResult.ok(userService.queryUserById(userId));}}
3、测试
在浏览器输入controller里面定义的路径即可。只要你按照上面的步骤一步一步来,基本上就没问题,是不是特别简单。
后
以上,就把Spring Boot整合Mybatis注释版 实现增删改查介绍完了,Spring Boot 整合Mybatis 是整个Spring Boot 非常重要的功能,也是非常核心的基础功能,希望大家能够熟练掌握。后面会深入介绍Spring Boot的各个功能和用法。
相关文章