Mybatis作为当今数据持久层开发的主流框架,作为后端开发必学框架之一
Mybatis-Generator插件可自动生成Dao、Model、Mapping相关文件,大大增加开发效率
现在让我们一起在SpringBoot中学习吧。
源码地址:https://github.com/JiBinXiao/springboot-all
本项目是在集成了dubbo分布式框架基础下,项目启动时请先启动zookeeper。
一.zookeeper安装-linux环境下
二.SpringBoot+Dubbo整合入门Demo
文章目录
一.在pom文件中添加Mybatis依赖
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
二.配置Mybatis数据源,application.properties文件添加配置信息
#mysql connection
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo
spring.datasource.username=root
spring.datasource.password=root
#mybatis
#注意:一定要对应mapper映射xml文件的所在路径
mybatis.mapper-locations=classpath:mappings/*.xml
#mybatis log
logging.level.com.xjb.data.provider.mapper=debug
三.springboot启动类,增加Mybatis扫描注解
@SpringBootApplication
@MapperScan("com.xjb.data.provider.mapper")
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class);
}
}
四.创建User表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`ctime` datetime DEFAULT NULL,
`utime` datetime DEFAULT NULL,
`st` int(1) DEFAULT '1' COMMENT '0:停用 1:使用',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
五.使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件
- pom中集成Mybatis-Generator插件
<build>
<plugins>
<!--mybatis自动生成表对象映射关系的 插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>tools/generator_sys.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
- 编写generator_sys.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动 这里请填写本地的绝对路径 -->
<classPathEntry location="C:/Users/xjb/.m2/repository/mysql/mysql-connector-java/5.1.34/mysql-connector-java-5.1.34.jar" />
<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/demo"
userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="com.xjb.data.api.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成映射文件的包名和位置 -->
<sqlMapGenerator targetPackage="com.xjb.data.provider.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.xjb.data.provider.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
<table tableName="user" domainObjectName="User"
enableCountByExample="fasle" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false" >
</table>
</context>
</generatorConfiguration>
- 运行插件,自动生成代码
- 进入idea的Maven Project–>Plugins找到mybatis-generator:generate双击运行生成相应文件
- 运行成功
- 代码结构
4. 将UserMapper.xml文件移动到resources的mappings文件下
六.增加TestCase,通过Junit测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void test1_Add() {
User user=new User();
user.setUsername("xjb");
user.setPassword("123456");
user.setCtime(new Date());
user.setUtime(new Date());
user.setSt(1);
userMapper.insertSelective(user);
}
@Test
public void test2_Query() {
User user = userMapper.selectByPrimaryKey(1);
Assert.assertNotNull(user);
}
@Test
public void test4_Upd() {
User user=new User();
user.setUsername("xjb");
user.setPassword("xjb");
user.setUtime(new Date());
user.setSt(1);
int i = userMapper.updateByPrimaryKeySelective(user);
Assert.assertEquals(1, i);
}
@Test
public void test5_Del() {
userMapper.deleteByPrimaryKey(1);
Assert.assertEquals(null, userMapper.selectByPrimaryKey(1));
}
}
七. 执行TestCase中的方法,验证Mybatis持久层方法是否正确
八.验证通过,编写Controller
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Reference(version = "1.0.0")
UserService userService;
@RequestMapping(value = "/sayHello")
public String sayHello(@RequestParam(defaultValue = "xjb") String name){
return userService.sayHello(name);
}
@RequestMapping(value = "add")
public String add(User user){
user.setCtime(new Date());
user.setUtime(new Date());
userService.add(user);
return "add success";
}
@RequestMapping(value = "findById")
public User findById(int id){
return userService.findById(id);
}
@RequestMapping(value = "update")
public String update(User user){
user.setUtime(new Date());
userService.update(user);
return "update success";
}
@RequestMapping(value = "delById")
public String delById(int id){
userService.delById(id);
return "delete success";
}
}
Mybatis注解版本:
优点:去除了配置文件,实现代码统一管理。
缺点:增加了Java代码的维护难度,不方便编写sql,可视化程度低。