MyBatis Generator是一款在使用mybatis框架时,自动生成model,dao和mapper的工具,很大程度上减少了业务开发人员的手动编码时间。
我们将使用这个工具自动化的构建 MVC 框架中 M 层所需要的东西。
在本地的数据库中创建一张表
# 创建数据库
CREATE DATABASE LEARNING CHARACTER SET utf8;
USE LEARNING;
# 创建表结构
CREATE TABLE ACCOUNT_INFO(
ACCOUNT_ID INTEGER PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
PWD VARCHAR(50),
BALANCE INTEGER
);
# 插入一条数据
INSERT INTO ACCOUNT_INFO VALUES(NULL,'root','root',100);
下载地址:
如果你是Windows用户,下载mysql-connector的时候可以选择 Platform Independent 版本
将下载好的MySQL驱动jar包放到generator的lib目录下,
确保mybatis-generator-core-1.3.6.jar
和mysql-connector-java-5.1.2.jar
在同一个目录下。
准备一个 configuration.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>
<!-- 配置驱动jar包路径.用了相对路径 -->
<classPathEntry location="mysql-connector-java-5.1.2.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 为了防止生成的代码中有很多注释,比较难看,加入下面的配置控制 -->
<commentGenerator>
<property name="suppressDate" value="true" />
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/LEARNING" userId="root"
password="********">
<property name="remarks" value="true" />
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 数据表对应的model 层 -->
<javaModelGenerator targetPackage="com.zdran.springboot.dao"
targetProject="D:\bxwzh">
<property name="enableSubPackages" value="true" />
</javaModelGenerator>
<!-- sql mapper 隐射配置文件 -->
<sqlMapGenerator targetPackage="com.zdran.springboot.mapping"
targetProject="D:\bxwzh">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 在ibatis2 中是dao层,但在mybatis3中,其实就是mapper接口 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.zdran.springboot.mapper" targetProject="D:\bxwzh">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要对哪些数据表进行生成操作,必须要有一个. -->
<table tableName="ACCOUNT_INFO" domainObjectName="AccountInfo"></table>
</context>
</generatorConfiguration>
注意:数据库的密码需要换成你自己的。targetProject=”D:\bxwzh,这个目录尽量是空文件夹
在 generator 的lib目录下执行下面的命令:
java -jar mybatis-generator-core-1.3.6.jar -configfile configuration.xml -overwrite
出现:MyBatis Generator finished successfully. 就说明成功了。
我们直接将com目录拷贝到项目目录下面去
在resources 新建 mybaits 目录,然后将 mapping 文件夹移动到 mybaits 下
现在我们的项目结构是下面这样的:
添加 mybaits依赖:
<!--springBoot和mybatis继承-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
<!-- 移除 logging -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.2</version>
</dependency>
在配置文件里添加下面的配置:
mybatis:
mapperLocations: classpath:mybatis/mapping/*.xml
typeAliasesPackage: com.zdran.springboot.dao
spring:
datasource:
name: test
url: jdbc:mysql://localhost:3306/LEARNING
username: root
password: ********
driver-class-name: com.mysql.jdbc.Driver
在 SpringbootApplication 类上面添加包的扫描路径
/**
* 启动程序
* Create by zdRan on 2018/6/28
*
* @author cm.zdran@gmail.com
*/
@SpringBootApplication
@MapperScan(basePackages = "com.zdran.springboot.mapper")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
下面我们实现一个根据姓名查询账号信息的接口。创建对应的controller、service等
Service 层的实现:
/**
* Create by ranzd on 2018/7/2
*
* @author cm.zdran@gmail.com
*/
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
AccountInfoMapper accountInfoMapper;
@Override
public AccountInfo queryByName(String name) {
AccountInfoExample example = new AccountInfoExample();
example.createCriteria().andNameEqualTo(name);
List<AccountInfo> accountInfoList = accountInfoMapper.selectByExample(example);
if (accountInfoList != null && accountInfoList.size() != 0) {
return accountInfoList.get(0);
}
return null;
}
}
Controller层的实现:
/**
* Create by ranzd on 2018/7/3
*
* @author cm.zdran@gmail.com
*/
@RestController
@RequestMapping("/account")
public class AccountController {
private Logger logger = LoggerFactory.getLogger(AccountController.class);
@Autowired
AccountService accountService;
@GetMapping("/get/{name}")
public AccountInfo getAccountByName(@PathVariable String name) {
logger.info("根据姓名获取账号信息。入参:name:{}", name);
AccountInfo accountInfo = accountService.queryByName(name);
if (accountInfo == null) {
logger.info("根据姓名获取账号信息。获取失败");
}
logger.info("根据姓名获取账号信息。出参:accountInfo:{}", accountInfo.toString());
return accountInfo;
}
}
运行一下,访问 http://localhost:9090/learning/account/get/root
url最后的 root 用户名
上面的配置方法是最简单的配置方法。还有一种常常用于生产环境的配置方法。
添加 druid 依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.1</version>
</dependency>
添加druid配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/LEARNING
username: root
password: ********
driver-class-name: com.mysql.jdbc.Driver
initialSize: 5
minIdle: 5
maxActive: 10
maxWait: 10000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
keepAlive: true
removeAbandoned: true
removeAbandonedTimeout: 80
logAbandoned: true
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,slf4j,wall
添加依赖,方便使用 ConfigurationProperties 注解,来读取yml里的配置信息
<!-- 为了方便使用@ConfigurationProperties注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
创建 druid 配置文件读取类
/**
* Create by ranzd on 2018/7/3
*
* @author cm.zdran@gmail.com
*/
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidDataSourceProperties {
private String driverClassName;
private String url;
private String username;
private String password;
private int initialSize;
private int minIdle;
private int maxActive;
private long maxWait;
private long timeBetweenEvictionRunsMillis;
private long minEvictableIdleTimeMillis;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean testWhileIdle;
private boolean keepAlive;
private boolean removeAbandoned;
private int removeAbandonedTimeout;
private boolean logAbandoned;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private String filters;
//省略了所有属性的 get 、set方法
}
上面的代码省略了所有属性的 get 、set方法,你的本地代码一定要有get、set方法
删除 yml 里的 mybaits 配置:
mybatis:
mapperLocations: classpath:mybatis/mapping/*.xml
typeAliasesPackage: com.zdran.springboot.dao
删除 SpringbootApplication 类上面的 MapperScan 注解
@MapperScan(basePackages = "com.zdran.springboot.mapper")
创建 mybaits 的配置类:
/**
* Create by ranzd on 2018/7/3
*
* @author cm.zdran@gmail.com
*/
@Configuration
@EnableTransactionManagement
@MapperScan(
basePackages = "com.zdran.springboot.mapper",
sqlSessionFactoryRef = "learningSqlSessionFactory")
public class MyBatisConfig {
private Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);
@Autowired
DruidDataSourceProperties druidDataSourceProperties;
@Bean(name = "learningSqlSessionFactory")
@Primary
public SqlSessionFactory learningSqlSessionFactory() throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(getDruidDataSource());
sessionFactory.setTypeAliasesPackage("com.zdran.springboot.dao");
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:/mybatis/mapping/*.xml"));
return sessionFactory.getObject();
}
@Bean(name = "learningDataSource")
public DataSource getDruidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(druidDataSourceProperties.getDriverClassName());
druidDataSource.setUrl(druidDataSourceProperties.getUrl());
druidDataSource.setUsername(druidDataSourceProperties.getUsername());
druidDataSource.setPassword(druidDataSourceProperties.getPassword());
druidDataSource.setInitialSize(druidDataSourceProperties.getInitialSize());
druidDataSource.setMinIdle(druidDataSourceProperties.getMinIdle());
druidDataSource.setMaxActive(druidDataSourceProperties.getMaxActive());
druidDataSource.setMaxWait(druidDataSourceProperties.getMaxWait());
druidDataSource.setTimeBetweenEvictionRunsMillis(
druidDataSourceProperties.getTimeBetweenEvictionRunsMillis());
druidDataSource.setMinEvictableIdleTimeMillis(
druidDataSourceProperties.getMinEvictableIdleTimeMillis());
druidDataSource.setTestOnBorrow(druidDataSourceProperties.isTestOnBorrow());
druidDataSource.setTestOnReturn(druidDataSourceProperties.isTestOnReturn());
druidDataSource.setTestWhileIdle(druidDataSourceProperties.isTestWhileIdle());
druidDataSource.setKeepAlive(druidDataSourceProperties.isKeepAlive());
druidDataSource.setRemoveAbandoned(druidDataSourceProperties.isRemoveAbandoned());
druidDataSource.setRemoveAbandonedTimeout(
druidDataSourceProperties.getRemoveAbandonedTimeout());
druidDataSource.setLogAbandoned(druidDataSourceProperties.isLogAbandoned());
druidDataSource.setPoolPreparedStatements(
druidDataSourceProperties.isPoolPreparedStatements());
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(
druidDataSourceProperties.getMaxPoolPreparedStatementPerConnectionSize());
try {
druidDataSource.setFilters(druidDataSourceProperties.getFilters());
druidDataSource.init();
} catch (SQLException e) {
logger.error("数据源初始化失败", e);
}
return druidDataSource;
}
}
OK!重新启动测试一下刚才的接口。