Mybatis动态sql & MyBatis Generator(MBG)

Mybatis动态sql

  1. if标签 - 多条件查询,获取用户列表;
  2. where标签 - 解决if标签拼接字符串AND符号问题;
		<select id="selectUserListByUser" parameterType="User" resultType="User">
		<!-- 查询用户性别,模糊查询用户名 查询用户cid  -->
		select * 
		from user
		<where>
		<!-- where标签可以去掉开头的and -->
		<if test="u_sex != null and u_sex != ''">
			u_sex=#{u_sex}
		</if>
		<if test="u_username != null and u_username != ''">
			and u_username like "%"#{u_username}"%"
		</if>
		<if test="u_cid != null">
			and u_cid = #{u_cid}
		</if>
		</where>
	
		</select>
  1. trim标签 - 定制where标签的规则
	<select id="selectUserListByUserTrim" parameterType="User" resultType="User">
		<!-- 查询用户性别,模糊查询用户名 查询用户cid  -->
		select * 
		from user
		<trim prefix="where" suffixOverrides="AND">
		
		<if test="u_sex != null and u_sex != ''">
		u_sex=#{u_sex} and
		</if>
		<if test="u_username != null and u_username != ''">
			 u_username like "%"#{u_username}"%" and
		</if>
		<if test="u_cid != null">
			 u_cid = #{u_cid}
		</if>
		</trim>
	</select>
  1. set标签 - 解决更新数据表时字符串拼接逗号”,”问题;
<!-- 	//更新用户表 -->
<!-- 	public void updateSetUser(User u); -->
	<update id="updateSetUser" parameterType="User">
		update user
		<set>
		<if test="u_username != null and u_username !=''">
			u_username = #{u_username},
		</if>
		<if test="u_password != null and u_password !=''">
			u_password = #{u_password},
		</if>
		<if test="u_sex != null and u_sex !=''">
			u_sex = #{u_sex }
		</if>
		</set>
		where
		u_id = #{u_id}
		
	</update>
  1. foreach标签 – 如果需要使用IN查询多条相同数据,可以使用foreach遍历;
<!-- 	//使用多个id获取用户列表 -->
<!-- 	public List<User> selectUserListByIds();(1,3,5) -->
	<select id="selectUserListByIds" resultType="User">
		SELECT * 
		FROM USER 
		WHERE u_id 
		IN 
		<!-- (1,2,3) -->
		<foreach collection="array" item="id" open="(" close=")" separator=",">
			#{id}
		</foreach>
	</select>
	
  • foreach中的collection指的是参数的类型,如array,list,以及自己定义的一些类型如list
  1. sql标签 – 可以提取重复sql语句片段;定义后通过include引用
<sql id="select">
	SELECT * FROM USER 
</sql>

<select id="" resultType="" resultMap="">
        <include refid="select"/>
</select>

MBG

  • 简介 根据数据库表自动生成Bean对象、Java接口及SqlMapper.xml配置文件
  • 基本步骤
    1. 导入依赖
    2. 创建geneeratorConfig.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="/Program Files/IBM/SQLLIB/java/db2java.zip" /> -->
  <context id="MyGererator" targetRuntime="MyBatis3">
  
  <!-- 这个标签可以去掉注释 -->
  <commentGenerator>
  <!-- 去掉注释 -->
  	<property name="suppressAllComments" value="true"/>
  <!-- 去掉时间戳 -->
  	<property name="suppressDate" value="true"/>
  </commentGenerator>
  
  
  <!-- 数据库连接信息 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/ssm_mybatis?useSSL=false&amp;serverTimezone=UTC"
        userId="root"
        password="***">
    </jdbcConnection>

	<!-- JAVA JDBC数据类型转换 -->
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

	<!--  javaModelGenerator javaBean配置
	targetPackage 输入包名 输出路径
	targetProject 输出项目位置 -->
    <javaModelGenerator targetPackage="com.my.bean" targetProject="src">
    <!-- enableSubPackages 是否开启子包名称 是否在包名后边加上scheme名称 -->
      <property name="enableSubPackages" value="false" />
      <!-- 在Set中加入.trim -->
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

	<!-- mapper.xml -->
    <sqlMapGenerator targetPackage="com.my.mapper"  targetProject="src">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>

	<!-- java接口  -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.my.mapper"  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>
  1. 创建一个java类生成文件
package com.my.test;

import java.io.File;
import java.io.IOException;
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, IOException {
		   List<String> warnings = new ArrayList<String>();
		   boolean overwrite = true;
		   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);
	}
}

  • main方法运行之后,对应的Bean对象、Java接口及SqlMapper.xml就生成了,当然前提是数据库中有表。
  • Junit测试
package com.my.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.my.bean.User;
import com.my.bean.UserExample;
import com.my.mapper.UserMapper;

public class MapperTest {
	@Test
	public void Test1() throws IOException {
		String resource = "sqlMapConfig.xml";
		//读取配置文件
		InputStream in = Resources.getResourceAsStream(resource);
		
		//需要ssqlSessionFactoryBulider
		SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
		
		
		//创建sqlSessionfactory
		SqlSessionFactory ssf = ssfb.build(in);
		//生产一个sqlSession
		SqlSession session = ssf.openSession();
		//操作数据库
		UserMapper mapper = session.getMapper(UserMapper.class);
		
		User user = mapper.selectByPrimaryKey(1);
		System.out.println(user);
	
		//使用example查询数据库
		UserExample example = new UserExample();
		example.createCriteria().andUSexEqualTo("1").andUUsernameLike("%王%");
		
		List<User> list = mapper.selectByExample(example);
		for (User user2 : list) {
			System.out.println(user2);
		}
	}
	
}

  • 这种方式生成的代码,对单表查询时极为方便
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值