手把手教mybatis 第四节

Mybatis之逆向工程

逆向工程

正向工程:建模(uml类图)—数据库设计—进行编码

逆向工程:进行数据库设计—uml类图----编码

mybatis-generator项目:根据数据库表结构自动生成 pojo实体类,生成映射文件,生成接口文件(包含了单表的CRUD)

官网:http://mybatis.org/generator/

搭建方式

  1. 采用eclipse的插件

  2. 命令行

    1. Create and fill out a configuration file appropriately (see below for samples)创建配置文件

    2. Save the file in some convenient location (like \temp\generatorConfig.xml)

    3. Run MBG from the command line with a command like this:

            java -jar mybatis-generator-core-x.x.x.jar -configfile \temp\generatorConfig.xml -overwrite
          
      

      This will tell MBG to run using your configuration file. It will also tell MBG to overwrite any existing Java or Kotlin files with the same name. If you want to save any existing files, then omit the -overwrite parameter. If there is a conflict, MBG will save the newly generated file with a unique name (e.g. MyClass.java.1).

    4. After running MBG, you will need to create or modify the standard MyBatis configuration make use of your newly generated code. See the Tasks After Running MyBatis Generator page for more information.

  3. with java

package com.sofwin;

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;

/**
 * 2023年7月10日
 * admin
 *
 */

public class Generator {

	public static void main(String[] args) throws Exception{
		// 创建集合,保存在逆向工程中的警告和错误信息
		 List<String> warnings = new ArrayList<String>();
		 // 是否覆盖
		   boolean overwrite = true;
		   // 创建file对象
		   File configFile = new File("D:\\eclipseworkspace202301\\generator\\src\\generatorConfiger.xml");
		   // 配置文件解析器
		   ConfigurationParser cp = new ConfigurationParser(warnings);
		   // 将配置文件解析为Configuration对象
		   Configuration config = cp.parseConfiguration(configFile);
		   // 设置回调
		   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		   // 创建MyBatisGenerator对象
		   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		   // 执行逆向工程
		   myBatisGenerator.generate(null);
	}
}

<!DOCTYPE generatorConfiguration PUBLIC
 "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 
 逆行工程的相关配置
 id:唯一标识
 targetRuntime:运行的目标
 defaultModelType:
	 conditional(默认)如果主键不是联合主键,主键和非主键字段共同
	    出现在一个实体类中。如果是联合主键,主键列单独创建一个实体类
	    非主键列单独创建一个实体类 extends 主键列创建的实体类
	 flat:不管有多少个主键,实体类只有一个
	 hierarchical:主键类会单独生成一个priamry class,单独对
	 blob类型进行了处理,blob类型的字段单独生成一个实体类
	 其他普通列单独生成一个实体类、
	 blob类型的字段称为大字段一般存储二进制的数据
	 text也可以等同于blob字段处理
 -->
  <context id="simple" targetRuntime="MyBatis3" defaultModelType="hierarchical">
  <!-- 
  配置数据库连接信息
  nullCatalogMeansCurrent:如果需要逆向的表的名称在dbms中的多个数据库下
  都有同名的表,表的字段变为了随机
  -->
    <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
        connectionURL="jdbc:mysql:///java2301q?nullCatalogMeansCurrent=true" userId="root" password="123456"/>

<!-- 实体类的生成位置
targetPackage:生成实体类的包名
targetProject:生成位置,默认是项目的根目录
  ./a/src
  实体类类名是按照大驼峰规则,去除_
  重点:不允许实体类前2个英文字母大写
-->
    <javaModelGenerator targetPackage="com.sofwin.pojo" targetProject="./src"/>
<!-- 
映射文件的生成位置
targetPackage:生成实体类的包名
targetProject:生成位置
-->
    <sqlMapGenerator targetPackage="com.sofwin.mapper" targetProject="./src">
    </sqlMapGenerator>
<!--
接口文件的生成位置
targetPackage:生成实体类的包名
targetProject:生成位置
-->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.sofwin.mapper" targetProject="./src"/>
<!-- 
table指定需要逆向的表
domainObjectName
 -->
    <table tableName="tb_goods" domainObjectName="Goods"/>
  </context>
</generatorConfiguration>

版本对应关系

RuntimeMyBatis Generator VersionMyBatis VersionMyBatis Dynamic SQL Version
MyBatis3, MyBatis3SimpleAny3.0+N/A
MyBatis3DynamicSQL1.3.6 - 1.3.73.4.2+1.1.0 - 1.2.1
MyBatis3DynamicSQL, MyBatis3Kotlin1.4.03.4.2+1.1.3+
MyBatis3DynamicSQL1.4.1+3.4.2+1.3.1+
MyBatis3Kotlin1.4.1+3.4.2+1.4.0+

下载核心依赖

逆行工程的相关配置

逆向工程的使用

方法名返回结果描述
int insert(TbUser row);影响行数执行Insert语句。所有字段都会出现在字段列表中,如果属性为null,插入null值
int insertSelective(TbUser row);影响行数执行Insert语句。不为空的字段出现在字段列表中,如果属性为Null,采用默认值
int updateByPrimaryKey(TbUser row);根据主键来更新(update,delete语句不允许没有查询条件),如果属性为null将字段更新为Null
int updateByPrimaryKeySelective(TbUser row);根据主键来更新,如果属性为null,不更新该字段
int updateByExample(@Param(“row”) TbUser row, @Param(“example”) TbUserExample example);更新,自定义条件进行更新
int updateByExampleSelective(@Param(“row”) TbUser row, @Param(“example”) TbUserExample example);更新,自定义条件进行更新,只更新不为空的列
int deleteByPrimaryKey(Integer id);通过主键删除
int deleteByExample(TbUserExample example);根据自定义条件删除
TbUser selectByPrimaryKey(Integer id);实体类根据主键查询对象,底层调用的selectOne
long countByExample(TbUserExample example);count(*)根据自定条件,查询数据库中的总条数
List selectByExample(TbUserExample example);集合根据自定义条件查询用户信息 selectList
selectByExampleWithBLOBs集合会封装blob类型字段对应的属性
updateByExampleWithBLOBs更新,会更新blob类型的字段
updateByPrimaryKeyWithBLOBs更新,会更新blob类型的字段,根据id更新
package com.sofwin.test;

import org.apache.ibatis.session.SqlSession;

import com.sofwin.mapper.TbUserMapper;
import com.sofwin.pojo.TbUser;
import com.sofwin.util.SqlSessionUtil;

/**
 * 2023年7月11日
 * admin
 *
 */

public class TestCreate {
	
	public static void main(String[] args) {
		SqlSession session = SqlSessionUtil.getSession();
		TbUserMapper mapper = session.getMapper(TbUserMapper.class);
		TbUser user = new TbUser();
		user.setName("helloWOrld");
		user.setLoginName("sofwin");
//		int flag = mapper.insert(user);
		int flag = mapper.insertSelective(user);
		System.out.println(flag);
	}

}

package com.sofwin.test;

import org.apache.ibatis.session.SqlSession;

import com.sofwin.mapper.TbUserMapper;
import com.sofwin.pojo.TbUser;
import com.sofwin.util.SqlSessionUtil;

/**
 * 2023年7月11日
 * admin
 *
 */

public class TestCreate {
	
	public static void main(String[] args) {
		SqlSession session = SqlSessionUtil.getSession();
		TbUserMapper mapper = session.getMapper(TbUserMapper.class);
		TbUser user = new TbUser();
		user.setName("helloWOrld1");
		user.setId(4);
		user.setSex(1);
		int flag = mapper.updateByPrimaryKeySelective(user);
		System.out.println(flag);
	}

}

int flag = mapper.deleteByPrimaryKey(4);

example

		// 默认使用 and 的运算符
		// id is null
       public Criteria andIdIsNull() {
            addCriterion("id is null");
            return (Criteria) this;
        }
		// 判断不为空
        public Criteria andIdIsNotNull() {
            addCriterion("id is not null");
            return (Criteria) this;
        }
		// 判断相等
        public Criteria andIdEqualTo(Integer value) {
            addCriterion("id =", value, "id");
            return (Criteria) this;
        }
		// 判断不相等
        public Criteria andIdNotEqualTo(Integer value) {
            addCriterion("id <>", value, "id");
            return (Criteria) this;
        }
		// 判断>
        public Criteria andIdGreaterThan(Integer value) {
            addCriterion("id >", value, "id");
            return (Criteria) this;
        }
		// 判断>=
        public Criteria andIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("id >=", value, "id");
            return (Criteria) this;
        }
		// 判断<
        public Criteria andIdLessThan(Integer value) {
            addCriterion("id <", value, "id");
            return (Criteria) this;
        }
		// 判断<=
        public Criteria andIdLessThanOrEqualTo(Integer value) {
            addCriterion("id <=", value, "id");
            return (Criteria) this;
        }
		// in子句
        public Criteria andIdIn(List<Integer> values) {
            addCriterion("id in", values, "id");
            return (Criteria) this;
        }
		// not in
        public Criteria andIdNotIn(List<Integer> values) {
            addCriterion("id not in", values, "id");
            return (Criteria) this;
        }
		// between
        public Criteria andIdBetween(Integer value1, Integer value2) {
            addCriterion("id between", value1, value2, "id");
            return (Criteria) this;
        }
		// not between
        public Criteria andIdNotBetween(Integer value1, Integer value2) {
            addCriterion("id not between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andNameIsNull() {
            addCriterion("name is null");
            return (Criteria) this;
        }

        public Criteria andNameIsNotNull() {
            addCriterion("name is not null");
            return (Criteria) this;
        }

        public Criteria andNameEqualTo(String value) {
            addCriterion("name =", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotEqualTo(String value) {
            addCriterion("name <>", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameGreaterThan(String value) {
            addCriterion("name >", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameGreaterThanOrEqualTo(String value) {
            addCriterion("name >=", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameLessThan(String value) {
            addCriterion("name <", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameLessThanOrEqualTo(String value) {
            addCriterion("name <=", value, "name");
            return (Criteria) this;
        }
		// 判断like
        public Criteria andNameLike(String value) {
            addCriterion("name like", value, "name");
            return (Criteria) this;
        }
		// not like
        public Criteria andNameNotLike(String value) {
            addCriterion("name not like", value, "name");
            return (Criteria) this;
        }

        public Criteria andNameIn(List<String> values) {
            addCriterion("name in", values, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotIn(List<String> values) {
            addCriterion("name not in", values, "name");
            return (Criteria) this;
        }

        public Criteria andNameBetween(String value1, String value2) {
            addCriterion("name between", value1, value2, "name");
            return (Criteria) this;
        }

        public Criteria andNameNotBetween(String value1, String value2) {
            addCriterion("name not between", value1, value2, "name");
            return (Criteria) this;
        }

        public Criteria andSexIsNull() {
            addCriterion("sex is null");
            return (Criteria) this;
        }

        public Criteria andSexIsNotNull() {
            addCriterion("sex is not null");
            return (Criteria) this;
        }

        public Criteria andSexEqualTo(Integer value) {
            addCriterion("sex =", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexNotEqualTo(Integer value) {
            addCriterion("sex <>", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexGreaterThan(Integer value) {
            addCriterion("sex >", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexGreaterThanOrEqualTo(Integer value) {
            addCriterion("sex >=", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexLessThan(Integer value) {
            addCriterion("sex <", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexLessThanOrEqualTo(Integer value) {
            addCriterion("sex <=", value, "sex");
            return (Criteria) this;
        }

        public Criteria andSexIn(List<Integer> values) {
            addCriterion("sex in", values, "sex");
            return (Criteria) this;
        }

        public Criteria andSexNotIn(List<Integer> values) {
            addCriterion("sex not in", values, "sex");
            return (Criteria) this;
        }

        public Criteria andSexBetween(Integer value1, Integer value2) {
            addCriterion("sex between", value1, value2, "sex");
            return (Criteria) this;
        }

        public Criteria andSexNotBetween(Integer value1, Integer value2) {
            addCriterion("sex not between", value1, value2, "sex");
            return (Criteria) this;
        }

        public Criteria andLoginNameIsNull() {
            addCriterion("login_name is null");
            return (Criteria) this;
        }

        public Criteria andLoginNameIsNotNull() {
            addCriterion("login_name is not null");
            return (Criteria) this;
        }

        public Criteria andLoginNameEqualTo(String value) {
            addCriterion("login_name =", value, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameNotEqualTo(String value) {
            addCriterion("login_name <>", value, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameGreaterThan(String value) {
            addCriterion("login_name >", value, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameGreaterThanOrEqualTo(String value) {
            addCriterion("login_name >=", value, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameLessThan(String value) {
            addCriterion("login_name <", value, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameLessThanOrEqualTo(String value) {
            addCriterion("login_name <=", value, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameLike(String value) {
            addCriterion("login_name like", value, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameNotLike(String value) {
            addCriterion("login_name not like", value, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameIn(List<String> values) {
            addCriterion("login_name in", values, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameNotIn(List<String> values) {
            addCriterion("login_name not in", values, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameBetween(String value1, String value2) {
            addCriterion("login_name between", value1, value2, "loginName");
            return (Criteria) this;
        }

        public Criteria andLoginNameNotBetween(String value1, String value2) {
            addCriterion("login_name not between", value1, value2, "loginName");
            return (Criteria) this;
        }
        
        // 添加or条件
        public void or(Criteria criteria) {
	    // 在原条件的基础上 后面增加or条件
	    // (and id and name) or ()
        oredCriteria.add(criteria);
        }
select count(*) from tb_user WHERE ( id = ? and id <> ? and id is null and id is not null and id > ? and id >= ? and id < ? and id <= ? and id in ( ? , ? , ? , ? ) and id not in ( ? , ? , ? , ? ) and id between ? and ? and id not between ? and ? and name like ? and name not like ? ) or (name='admin')
package com.sofwin.test;

import java.util.Arrays;

import org.apache.ibatis.session.SqlSession;

import com.sofwin.mapper.TbUserMapper;
import com.sofwin.pojo.TbUser;
import com.sofwin.pojo.TbUserExample;
import com.sofwin.pojo.TbUserExample.Criteria;
import com.sofwin.util.SqlSessionUtil;

/**
 * 2023年7月11日
 * admin
 *
 */

public class TestCreate {
	
	public static void main(String[] args) {
		SqlSession session = SqlSessionUtil.getSession();
		TbUserMapper mapper = session.getMapper(TbUserMapper.class);
		TbUserExample example = new TbUserExample();
		// 创建一组查询条件(该criteria下所有的方法在作为条件时都会用())
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(1);// and id=1
		criteria.andIdNotEqualTo(1);// and id <>1
		criteria.andIdIsNull();// and id is null
		criteria.andIdIsNotNull();// and id is not null
		criteria.andIdGreaterThan(10);// and id>10
		criteria.andIdGreaterThanOrEqualTo(10);// and id>=10
		criteria.andIdLessThan(10);// and id<10
		criteria.andIdLessThanOrEqualTo(10);// and id<=10
		criteria.andIdIn(Arrays.asList(1,2,3,4));// and id in(1,2,3,4)
		criteria.andIdNotIn(Arrays.asList(1,2,3,4));// and id not in(1,2,3,4)
		criteria.andIdBetween(1, 10);// and id between 1 and 10
		criteria.andIdNotBetween(1, 10);// and id not between 1 and 10
		// 占位符
		criteria.andNameLike("%a%");// and name like '%a%'
		criteria.andNameNotLike("%a%");// and name not like '%a%'
		Criteria criteria2 = example.createCriteria();
		criteria2.andNameEqualTo("admin");
		// 增加or的条件
		example.or(criteria2);
		// 去重
		example.setDistinct(true);
		// 添加排序字段列表  提供了order by 
		example.setOrderByClause(" id desc,name asc,login_name asc");
		mapper.selectByExample(example);
	}

}

@Param

允许接口文件中的抽象方法有2个参数,多个输入参数转为了map类型

 int updateByExample(@Param("row") TbUser row, @Param("example") TbUserExample example);

作业

1.练习逆向工程搭建

2.练习逆向工程的所有方法

注解(不推荐)

优点:开发效率高

缺点:硬编码

@Insert

	@Insert("insert into tb_user(name,sex,login_name) values(#{name},#{sex},#{loginName})")
	int insertUser(TbUser user);

@Update

	@Update("update tb_user set name=#{name},sex=#{sex},login_name=#{loginName} where id=#{id}")
	int updateById(TbUser user);
	

@Delete

@Delete("delete from tb_user where id=#{id}")
	int deleteById(Integer id);

@Select

默认采用了同名的结果映射

@Select("select id,name,sex,login_name loginName from tb_user where id=#{id}")
	TbUser selectById(Integer id);

@Results

进行不同名的结果映射,相等于

@Select("select * from tb_user where id=#{id}")
	@Results(id="map1",value= {
			@Result(id=true,column="id",property = "id"),
			@Result(id=false,column="name",property = "name"),
			@Result(id=false,column = "sex",property = "sex"),
			@Result(id=false,column = "login_name",property = "loginName")
	})
	TbUser selectById(Integer id);

@ResultMap

对Results标签的引用

@Select("select * from tb_user where id=#{id}")
	@ResultMap("map1")
	TbUser selectById2(Integer id);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_AndyLau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值