JavaWeb_(Mybatis框架)MyBatis Generator简单入门
官方文档 传送门
下载地址 传送门
MyBatis Generator(MBG)简介:
MyBatis Generator(MBG)是MyBatis MyBatis 和iBATIS的代码生成器。它将为所有版本的MyBatis以及版本2.2.0之后的iBATIS版本生成代码。它将内省数据库表(或许多表),并将生成可用于访问表的工件。这减少了设置对象和配置文件以与数据库表交互的初始麻烦。MBG寻求对简单CRUD(创建,检索,更新,删除)的大部分数据库操作产生重大影响。您仍然需要为连接查询或存储过程手动编写SQL和对象代码。
创建一个简单的MyBatis Generator项目
1、搭建MBG项目;
a)下载MBG核心包;
b)创建java项目;
c)从官方文档获取配置表、实例代码;
d)导入依赖包;
2、MBG配置以及根据数据库表生成所需文件(Bean、Interface、Mapper.xml);
3、使用自动生成的文件操作数据库;
准备数据库
/*
SQLyog Professional v12.08 (64 bit)
MySQL - 5.5.49 : Database - ssm_mybatis
*********************************************************************
*/ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssm_mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `ssm_mybatis`; /*Table structure for table `country` */ DROP TABLE IF EXISTS `country`; CREATE TABLE `country` (
`c_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '国家id',
`c_countryname` varchar(128) NOT NULL COMMENT '国家名称',
`c_capital` varchar(128) DEFAULT NULL COMMENT '国家首都名称',
PRIMARY KEY (`c_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; /*Data for the table `country` */ insert into `country`(`c_id`,`c_countryname`,`c_capital`) values (1,'中国','北京'),(3,'美国','华盛顿'),(4,'英国','伦敦'),(5,'日本','东京'); /*Table structure for table `user` */ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` (
`u_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`u_username` varchar(64) NOT NULL COMMENT '用户名',
`u_password` varchar(64) DEFAULT NULL COMMENT '用户密码',
`u_sex` varchar(16) DEFAULT NULL COMMENT '用户性别',
`u_createTime` datetime DEFAULT NULL COMMENT '用户创建时间',
`u_cid` int(11) DEFAULT NULL COMMENT '用户国家id',
PRIMARY KEY (`u_id`),
KEY `FK_user_cid` (`u_cid`),
CONSTRAINT `FK_user_cid` FOREIGN KEY (`u_cid`) REFERENCES `country` (`c_Id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8; /*Data for the table `user` */ insert into `user`(`u_id`,`u_username`,`u_password`,`u_sex`,`u_createTime`,`u_cid`) values (1,'老王','','',NULL,1),(2,'jack','','',NULL,3),(3,'alice','ali111','',NULL,3),(4,'王司机','','',NULL,1),(5,'anna','ali111','',NULL,4),(6,'李师傅','','',NULL,1),(7,'漩涡鸣人','','',NULL,5),(8,'娜美','','',NULL,5),(9,'王五','abc','',NULL,1),(10,'老赵',NULL,NULL,NULL,NULL),(11,'老孙',NULL,NULL,NULL,NULL),(12,'98k',NULL,NULL,NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
ssm_mybatis.sql
package com.Gary.test; 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 Generator { public static void main(String[] args) throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//读取src目录下generatorConfig.xml配置文件
File configFile = new File("src/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);
} }
Generator.java
<?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> </generatorConfiguration>
generatorConfig.xml
Mybatis-Generator-Config配置及生成所需文件
<!-- 配置数据库链接的包 jar包已经放到项目中 -->
<!-- <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> <context id="MyGenerator" targetRuntime="MyBatis3">
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_mybatis"
userId="root"
password="123456">
</jdbcConnection> <!-- JAVA JDBC类型转换 配置信息的转换规则 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- 重点 javaModelGenerator javaBean配置
targetPackage 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.Gary.bean" targetProject="src">
<!-- 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set中加入trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator> <!-- mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator> <!-- java接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator> <!-- 数据库中的表 根据数据库中表来生成 -->
<table tableName="user"/>
<table tableName="country"/> <!--
<table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
<property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="DB2" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table>
--> </context>
<?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="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> <context id="MyGenerator" targetRuntime="MyBatis3">
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_mybatis"
userId="root"
password="123456">
</jdbcConnection> <!-- JAVA JDBC类型转换 配置信息的转换规则 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- 重点 javaModelGenerator javaBean配置
targetPackage 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.Gary.bean" targetProject="src">
<!-- 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set中加入trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator> <!-- mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator> <!-- java接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator> <!-- 数据库中的表 根据数据库中表来生成 -->
<table tableName="user"/>
<table tableName="country"/> <!--
<table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
<property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="DB2" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table>
--> </context>
</generatorConfiguration>
generatorConfig.xml
执行Generator.java代码后Refresh,可以看到Generator帮我们生成好了一系列的工程文件
package com.Gary.test; 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 Generator { public static void main(String[] args) throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//读取src目录下generatorConfig.xml配置文件
File configFile = new File("src/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);
} }
Generator.java
<?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="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> <context id="MyGenerator" targetRuntime="MyBatis3">
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_mybatis"
userId="root"
password="123456">
</jdbcConnection> <!-- JAVA JDBC类型转换 配置信息的转换规则 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- 重点 javaModelGenerator javaBean配置
targetPackage 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.Gary.bean" targetProject="src">
<!-- 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set中加入trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator> <!-- mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator> <!-- java接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator> <!-- 数据库中的表 根据数据库中表来生成 -->
<table tableName="user"/>
<table tableName="country"/> <!--
<table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
<property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="DB2" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table>
--> </context>
</generatorConfiguration>
generatorConfig.xml
发现Generator帮我们自动生成了很多元素的注释,可以在generatorConfig.xml中配置不需要生成这些注释
<!-- 这个标签可以去掉注释 -->
<commentGenerator>
<!-- 去掉注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 去掉时间戳 -->
<property name="suppressDate" value="true"/>
</commentGenerator>
Generator使用生成的文件操作数据库
在user对象中生成toString()方法
测试:
一、按主键查询语句
//按主键查询
User user = mapper.selectByPrimaryKey(1);
System.out.println(user);
二、条件查询语句
UserExample example = new UserExample();
//将条件封装到createCriteria集合中
example.createCriteria().andUSexEqualTo("1").andUUsernameLike("%王%"); //按条件查询
List<User> list = mapper.selectByExample(example); for (User user : list) {
System.out.println(user);
}
三、插入数据语句
User user = new User() ;
user.setuUsername("赵云"); mapper.insertSelective(user); session.commit();
package com.Gary.test; import java.io.IOException;
import java.io.InputStream;
import java.util.List; 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.junit.Test; import com.sikiedu.bean.User;
import com.sikiedu.bean.UserExample;
import com.sikiedu.mapper.UserMapper; public class MapperTest { @Test
public void Test1() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource );
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
SqlSession session = ssf.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); //按住键查询
User user = mapper.selectByPrimaryKey(1);
System.out.println(user);
} @Test
public void Test2() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource );
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
SqlSession session = ssf.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); UserExample example = new UserExample();
//将条件封装到createCriteria集合中
example.createCriteria().andUSexEqualTo("1").andUUsernameLike("%王%"); //按条件查询
List<User> list = mapper.selectByExample(example); for (User user : list) {
System.out.println(user);
} } @Test
public void Test3() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource );
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
SqlSession session = ssf.openSession(); UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User() ;
user.setuUsername("赵云"); mapper.insertSelective(user); session.commit();
} }
MapperTest.java
JavaWeb_(Mybatis框架)MyBatis Generator简单入门的更多相关文章
- Mybatis框架学习1:入门
一框架介绍 1.Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google c ...
- 深入学习Mybatis框架(一)- 入门
1.什么是Mybatis? Mybatis是一个优秀持久层框架,提供了对数据库的一系列操作(增删改查).Mybatis可以避免重复的写JDBC代码,让我们以较少的代码实现对数据库的操作,从而提高开发效 ...
- JavaWeb_(Mybatis框架)MyBatis整合Spring框架
MyBatis + Spring整合开发 a)使用Spring容器用单例模式管理Mybatis的sqlSessionFactory:b)使用Spring管理连接池.数据源等:c)将Dao/Mapper ...
- 框架之 hibernate简单入门
hibernate框架的搭建 Hibernate框架的概述 1. Hibernate框架的概述 * Hibernate称为 * Hibernate是一个开放源代码的对象关系映射(ORM)框架,它对JD ...
- MyBatis框架——mybatis插入数据返回主键(mysql、oracle)
向数据库中插入数据时,大多数情况都会使用自增列或者UUID做为主键.主键的值都是插入之前无法知道的,但很多情况下我们在插入数据后需要使用刚刚插入数据的主键,比如向两张关联表A.B中插入数据(A的主键是 ...
- MyBatis - 介绍、简单入门程序
JDBC编程中的问题 1. 将SQL语句硬编码到Java代码,不利于系统维护. 设想如何解决:将SQL单独抽取出来,在配置文件(xml方式.properties文件)进行配置. ...
- myBatis框架之入门(一)
什么是框架 框架就是一个架子,表演节目,舞台已经搭建好,表演什么节目,看自己的需求了. 框架是一个半成品,对于Java语言来说,框架就是封装了别人的代码.在框架的基础上我们在进一步开发,拿来主义. 框 ...
- Mybatis框架中实现双向一对多关系映射
学习过Hibernate框架的伙伴们很容易就能简单的配置各种映射关系(Hibernate框架的映射关系在我的blogs中也有详细的讲解),但是在Mybatis框架中我们又如何去实现 一对多的关系映射呢 ...
- Mybatis框架(9)---Mybatis自定义插件生成雪花ID做为表主键项目
Mybatis自定义插件生成雪花ID做为主键项目 先附上项目项目GitHub地址 spring-boot-mybatis-interceptor 有关Mybatis雪花ID主键插件前面写了两篇博客作为 ...
随机推荐
- (二) JPA基础
一.什么是JAP JPA(Java Persistence API)是SUN官方推出的Java持久化规范,它为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据.它的出现主要是 ...
- 解决https 请求过程中SSL问题
最近一个项目中用到了https的请求,在实际调用过程中发现之前的http方法不支持https,调用一直报错. 查询了一下,添加几行代码解决问题. public string HttpPost(stri ...
- Zookeeper 安装及集群配置注意点
Zookeeper在ubuntu下安装及集群搭建,关于集群搭建,网上很多文章 可以参考:https://www.ibm.com/developerworks/cn/opensource/os-cn-z ...
- svnkit 用java 操作 svn
官网 https://svnkit.com/ https://blog.csdn.net/Hui_hai/article/details/80318518 https://blog.csdn.net/ ...
- form表单提交后结果乱码的解决方法
1.产生乱码原因:表单提交使用的method="get",get方式数据都是通过地址栏传输,数据会以iso-8859-1方式传输,因此产生乱码 2.概念:URI: Uniform ...
- vue中使用ts后,父组件获取执行子组件方法报错问题
一.问题产生背景: 子组件的一个方法: update () { this.$nextTick(() => { this.ul_slots.forEach((ul, cur_slots_index ...
- 自定义centos
目录 自定义centos 1. 为什么要自定义centos 2. 自定义centos步骤 自定义centos 1. 为什么要自定义centos 在使用官网的 centos镜像,只有200m,很小,但是 ...
- Sharing is only supported for boot loader classes because bootstrap classpath has been appended
在idea里面运行项目,terminal里面报“Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boo ...
- fwrite、write、fread、read
1. write和read 1.1 write: 头文件:#include<unistd.h> 原型: ssize_t write(int fd,const void*buf,size_t ...
- 【前端】低版本IE浏览器访问网站一片空白
最近在客户那里,发现一个奇葩的问题,系统上IE浏览器访问网站一片空白,显示无法访问. 但是相同的网站系统,在我们的电脑上又可以访问且IE浏览器版本相同,没法只有,装虚拟模拟客户环境复现一下了. 发现在 ...