mybatis-210721-08---动态sql-sql标签抽取可重用的sql

mybatis-210721-08—动态sql-sql标签抽取可重用的sql


EmployeeMapper.java

package com.bgy.mybatis.dao;
import com.bgy.mybatis.bean.Employee;

public interface EmployeeMapper {
	
	public void insertEmps(Employee employee);
}

EmployeeMapper.xml(笔记在这儿哦)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bgy.mybatis.dao.EmployeeMapper">
	
	
	<!-- 
		抽取可重用的sql片段,方便以后引用
		
		1、将经常要查询的列明,或者插入用的列明,抽取出来,方便引用。
		2、include标签用来引用已经抽取的sql
		3、include可以自定义一些property,sql标签就能使用,以下举例
		   使用  ${property}  取值
			<sql id="inserColumn">
				<if test="_databaseId=='mysql'">
					last_name,gender,email,d_id,${realname}
				</if>
				<if test="_databaseId=='oracle'">
					last_name,gender,email,d_id
				</if>
			</sql>
			
			<include refid="inserColumn">
				<property name="realname" value="myname"/>
			</include>
		
		
		sql标签里面同样可以写动态标签
	-->
	<sql id="inserColumn">
		<if test="_databaseId=='mysql'">
			last_name,gender,email,d_id
		</if>
		<if test="_databaseId=='oracle'">
			last_name,gender,email,d_id
		</if>
	</sql>
	
	<insert id="insertEmps">
		insert into
			tbl_employee(
				<!-- include 标签就是引用外部定义的sql -->
				<include refid="inserColumn">
				</include>
			)
		values(#{lastName},#{gender},#{email},#{dept.id})
	</insert>
</mapper>

MybatisTest.java

package com.bgy.mybatis.test;

import java.io.IOException;
import java.io.InputStream;

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.jupiter.api.Test;

import com.bgy.mybatis.bean.Department;
import com.bgy.mybatis.bean.Employee;
import com.bgy.mybatis.dao.EmployeeMapper;

class MybatisTest {
	
	public SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}

	
	/**·
	 * 测试sql——sql标签-抽取可充的sql片段
	 * @throws IOException
	 */
	@Test
	public void test() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		try {
			EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
			
			mapper.insertEmps(new Employee(null,"yuji","yuji@qq.com","0",new Department(1)));
			
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值