超级通道:MyBatis代码实例系列-绪论
本章主要记录如何使用Mybatis Generator,并在其基础上进行扩展优化,涉及到的技术有:
- MyBatis Generator:MyBatis代码自动生成插件,能够生成实体.java、实体Mapper.java和实体Mapper.xml,注释为英文
- [email protected]:li24361/mybatis-generator-core.git:开源插件,对MyBatis Generator进行了扩展,实现了中文注释,并将生成结果重命名为:实体Entity.java、实体Dao.java和实体Dao.xml。
- generatorConfig.xml:MyBatis Generator的配置文件。
- ToStringPlugin:MyBatis Generator的插件,在实体类中自动生成toString()方法。
- EqualsHashCodePlugin:MyBatis Generator的插件,在实体类中自动添加hashCode()和Equals()方法。
在使用MyBatis框架进行开发时,每用到一张表就要手动创建实体类、XML映射文件和映射接口,这些都是重复性工作,耗费了我们大量精力。
MyBatis Generator (简称MBG) 是一个Mybatis的代码生成器。它可以根据数据库中的表,生成对应的实体类、XML映射文件和映射接口,节约了大量的时间去开发和业务逻辑有关的功能。
当然,如果是多表联合查询和存储过程,仍然需要手动处理。
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.6version>
dependency>
<plugins>
...
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.6version>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
dependencies>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xmlconfigurationFile>
<overwrite>trueoverwrite>
<verbose>trueverbose>
configuration>
<executions>
<execution>
<id>MyBatis Generatorid>
<goals>
<goal>generategoal>
goals>
execution>
executions>
plugin>
...
plugins>
<generatorConfiguration>
<properties resource="jdbc.properties"/>
<context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<commentGenerator>
<property name="suppressAllComments" value="false"/>
<property name="suppressDate" value="true"/>
commentGenerator>
<jdbcConnection driverClass="${jdbc.driverClassName}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}">
jdbcConnection>
<javaModelGenerator targetPackage="pers.hanchao.himybatis.generator.entity" targetProject="src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true" />
javaModelGenerator>
<sqlMapGenerator targetPackage="generator" targetProject="src\main\resources">
<property name="enableSubPackages" value="true"/>
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="pers.hanchao.himybatis.generator.dao" targetProject="src\main\java">
<property name="enableSubPackages" value="true"/>
javaClientGenerator>
<table schema="exam" tableName="topic">
<generatedKey column="id" sqlStatement="Mysql"/>
table>
context>
generatorConfiguration>
在IDEA
中,点击Edit Configurations
–>添加一个Maven
配置
–>录入Name
–>Command Line录入:mybatis-generator:generate
–>点击OK
保存配置
–>点击或通过Alt+Shift+X
运行这个Maven
配置
生成目录如下:
src
\---main
\---java
| \---pers
| \---hanchao
| \---himybatis
| \---generator
| \---dao
| | \---TopicMapper.java
| |---entity
| \---Topic.java
\---webapp
\---generator
\---TopicMapper.xml
代码展示:
Topic.java
只详细展示第一个字段,后续字段和方法略。
package pers.hanchao.himybatis.generator.entity;
public class Topic {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column topic.id
*
* @mbg.generated
*/
private Integer id;
//other field
//setter getter toString hashCode equals
}
TopicMapper.java
只详细展示第一个方法,后续方法略。
package pers.hanchao.himybatis.generator.dao;
import java.util.List;
import pers.hanchao.himybatis.generator.entity.Topic;
public interface TopicMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table topic
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
//int insert(Topic record);
//Topic selectByPrimaryKey(Integer id);
//List selectAll();
//int updateByPrimaryKey(Topic record);
}
TopicMapper.xml
只详细展示第一个方法,后续方法略。
<mapper namespace="pers.hanchao.himybatis.generator.dao.TopicMapper">
<resultMap id="BaseResultMap" type="pers.hanchao.himybatis.generator.entity.Topic">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="title" jdbcType="VARCHAR" property="title" />
<result column="score" jdbcType="INTEGER" property="score" />
<result column="answer" jdbcType="VARCHAR" property="answer" />
resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from topic
where id = #{id,jdbcType=INTEGER}
delete>
mapper>
有待改进之处:
XxxxMapper
全部修改为XxxxDao
。鉴于以上原因,很多大牛们通过修改MyBatis Generator源码或者新增实现类,提供了各种各样的解决方案。
本章只详细介绍其中的一种方案:由li24361
提供的https://github.com/li24361/mybatis-generator-core
将mybatis-generator-core
项目克隆到本地
git clone git@github.com:li24361/mybatis-generator-core.git
将mybatis-generator-core
打成jar包并存放到本地仓库中
cd mybatis-generator-core/
mvn install -Dmaven.test.skip=true
注意:mybatis-generator-maven-plugin的版本号是1.3.2
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.2version>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>com.haier.hairygroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.0.1version>
dependency>
dependencies>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xmlconfigurationFile>
<overwrite>trueoverwrite>
<verbose>trueverbose>
configuration>
plugin>
<commentGenerator type="org.mybatis.generator.internal.HairyCommentGenerator">
<property name="javaFileEncoding" value="UTF-8"/>
<property name="suppressAllComments" value="false"/>
<property name="suppressDate" value="true"/>
commentGenerator>
生成目录如下:
src
\---main
\---java
| \---pers
| \---hanchao
| \---himybatis
| \---generator
| \---dao
| | \---TopicDao.java
| |---entity
| \---TopicEntity.java
\---webapp
\---generator
\---TopicDao.xml
代码展示:
TopicEntity.java
只详细展示第一个字段,后续字段和方法略。
package pers.hanchao.himybatis.generator.entity;
public class TopicEntity {
/**
*
* 话题
* 表字段 : topic.id
*
*/
private Integer id;
//other fields
//setter getter toString hashCode equals
}
TopicDao.java
只详细展示第一个方法,后续方法略。
package pers.hanchao.himybatis.generator.dao;
import java.util.List;
import pers.hanchao.himybatis.generator.entity.TopicEntity;
public interface TopicDao {
/**
* 根据主键删除数据库的记录
*
* @param id
*/
int deleteByPrimaryKey(Integer id);
//int insert(Topic record);
//Topic selectByPrimaryKey(Integer id);
//List selectAll();
//int updateByPrimaryKey(Topic record);
}
TopicDao.xml的内容和之前一样,不再赘述。
总结:通过使用由li24361
提供的https://github.com/li24361/mybatis-generator-core,确实达到了之前的目的:
通过简单的TopicApp.java
完成对生成的TopicEntity.java、TopicDao.java、TopicDao.xml可用性测试。
TopicApp.java
package pers.hanchao.himybatis.generator;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import pers.hanchao.himybatis.generator.dao.TopicDao;
import pers.hanchao.himybatis.generator.entity.TopicEntity;
import java.io.IOException;
import java.io.Reader;
/**
* 测试MyBatis Generator生成的代码是否可用
* @author hanchao 2018/2/4 10:45
**/
public class TopicApp {
/** 日志 */
private static final Logger LOGGER = Logger.getLogger(TopicApp.class);
/** 配置文件读取类 */
private static Reader reader;
/** 会话工厂 */
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//读取配置文件
reader = Resources.getResourceAsReader("mybatis-config-generator.xml");
//构建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 对MyBatis Generator生成的数据库方法进行测试
* @author hanchao 2018/2/4 10:46
**/
public static void main(String[] args) {
//创建会话
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//获取Dao层实例
TopicDao topicDao = sqlSession.getMapper(TopicDao.class);
//查询所有
LOGGER.info("查询所有");
LOGGER.info(topicDao.selectAll());
//插入一个,查询所有
System.out.println();
LOGGER.info("插入一个");
TopicEntity newTopic = new TopicEntity();
newTopic.setId(100);
newTopic.setTitle("新增的标题");
newTopic.setScore(200);
newTopic.setAnswer("新增的答案");
topicDao.insert(newTopic);
LOGGER.info(topicDao.selectAll());
//查询一个
System.out.println();
LOGGER.info("查询一个");
LOGGER.info(topicDao.selectByPrimaryKey(1));
//修改一个,然后查询
System.out.println();
LOGGER.info("修改一个");
newTopic = new TopicEntity();
newTopic.setId(1);
newTopic.setTitle("修改的标题");
newTopic.setScore(1000);
newTopic.setAnswer("修改的答案");
topicDao.updateByPrimaryKey(newTopic);
LOGGER.info(topicDao.selectByPrimaryKey(1));
//删除一个,然后查询
System.out.println();
LOGGER.info("删除一个,然后查询");
topicDao.deleteByPrimaryKey(1);
LOGGER.info(topicDao.selectByPrimaryKey(1));
//提交
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
LOGGER.info("error!");
sqlSession.rollback();
}finally {
sqlSession.close();
}
}
}
运行结果:
2018-02-04 16:38:59 INFO TopicApp:49 - 查询所有
2018-02-04 16:38:59 DEBUG JdbcTransaction:54 - Opening JDBC Connection
2018-02-04 16:39:00 DEBUG PooledDataSource:54 - Created connection 1316864772.
2018-02-04 16:39:00 DEBUG JdbcTransaction:54 - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4e7dc304]
2018-02-04 16:39:00 DEBUG selectAll:54 - ==> Preparing: select id, title, score, answer from topic
2018-02-04 16:39:00 DEBUG selectAll:54 - ==> Parameters:
2018-02-04 16:39:00 DEBUG selectAll:54 - <== Total: 2
2018-02-04 16:39:00 INFO TopicApp:50 - [TopicEntity [Hash = -756562783, id=1, title=新话题1111, score=1001111, answer=新答案111], TopicEntity [Hash = 1936880702, id=99999, title=题目1, score=100, answer=你好吗?]]
2018-02-04 16:39:00 INFO TopicApp:53 - 插入一个
2018-02-04 16:39:00 DEBUG insert!selectKey:54 - ==> Preparing: SELECT LAST_INSERT_ID()
2018-02-04 16:39:00 DEBUG insert!selectKey:54 - ==> Parameters:
2018-02-04 16:39:00 DEBUG insert!selectKey:54 - <== Total: 1
2018-02-04 16:39:00 DEBUG insert:54 - ==> Preparing: insert into topic (id, title, score, answer) values (?, ?, ?, ?)
2018-02-04 16:39:00 DEBUG insert:54 - ==> Parameters: 0(Integer), 新增的标题(String), 200(Integer), 新增的答案(String)
2018-02-04 16:39:00 DEBUG insert:54 - <== Updates: 1
2018-02-04 16:39:00 DEBUG selectAll:54 - ==> Preparing: select id, title, score, answer from topic
2018-02-04 16:39:00 DEBUG selectAll:54 - ==> Parameters:
2018-02-04 16:39:00 DEBUG selectAll:54 - <== Total: 3
2018-02-04 16:39:00 INFO TopicApp:60 - [TopicEntity [Hash = -756562783, id=1, title=新话题1111, score=1001111, answer=新答案111], TopicEntity [Hash = 1936880702, id=99999, title=题目1, score=100, answer=你好吗?], TopicEntity [Hash = -1744254903, id=100001, title=新增的标题, score=200, answer=新增的答案]]
2018-02-04 16:39:00 INFO TopicApp:63 - 查询一个
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Preparing: select id, title, score, answer from topic where id = ?
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Parameters: 1(Integer)
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - <== Total: 1
2018-02-04 16:39:00 INFO TopicApp:64 - TopicEntity [Hash = -756562783, id=1, title=新话题1111, score=1001111, answer=新答案111]
2018-02-04 16:39:00 INFO TopicApp:67 - 修改一个
2018-02-04 16:39:00 DEBUG updateByPrimaryKey:54 - ==> Preparing: update topic set title = ?, score = ?, answer = ? where id = ?
2018-02-04 16:39:00 DEBUG updateByPrimaryKey:54 - ==> Parameters: 修改的标题(String), 1000(Integer), 修改的答案(String), 1(Integer)
2018-02-04 16:39:00 DEBUG updateByPrimaryKey:54 - <== Updates: 1
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Preparing: select id, title, score, answer from topic where id = ?
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Parameters: 1(Integer)
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - <== Total: 1
2018-02-04 16:39:00 INFO TopicApp:74 - TopicEntity [Hash = 1122539663, id=1, title=修改的标题, score=1000, answer=修改的答案]
2018-02-04 16:39:00 INFO TopicApp:77 - 删除一个,然后查询
2018-02-04 16:39:00 DEBUG deleteByPrimaryKey:54 - ==> Preparing: delete from topic where id = ?
2018-02-04 16:39:00 DEBUG deleteByPrimaryKey:54 - ==> Parameters: 1(Integer)
2018-02-04 16:39:00 DEBUG deleteByPrimaryKey:54 - <== Updates: 1
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Preparing: select id, title, score, answer from topic where id = ?
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Parameters: 1(Integer)
2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - <== Total: 0
2018-02-04 16:39:00 INFO TopicApp:79 -
参考资料:
更多扩展: