Mybatis的mapper代理

2022-08-13 12:47:13

mybatis的mapper代理

mybatis的mapper代理代替了dao的实现类(将dao的实现类写在了xml文件中)

mapper.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"><!-- namespace不能为空
	mapper:相当于java里面的类
	namespace:相当于java里面的包名
	
	要想使用Mapper代理,有要求:~namespace必须是Dao接口的包名+类名~sql标签中的id必须和dao接口中的方法名一样~parameterType:必须和dao接口方法中的形参类型一样;(木有提到形参的名字)~resultType:必须和dao接口方法中的返回值类型一样;--><mapper namespace="com.jinghangzz.mybatis.data.dao.IADemoDynastyDao"><!-- 
		查询所有的朝代记录
		select标签可以发送select语句
		
		id:唯一标识,当前的mapper文件中,id不能重复
		resultType:结果类型;
			如果查询的是单条,那返回值的类型就是resultType; 
			如果查询的是多条,那么返回值的类型是List,List里面放的是resultType--><select id="selectList" resultType="com.jinghangzz.mybatis.data.pojo.ADemoDynasty">
		select* from a_demo_dynasty</select><!-- 保存一条记录--><insert id="saveOneDao" parameterType="com.jinghangzz.mybatis.data.pojo.ADemoDynasty"
		useGeneratedKeys="true" keyColumn="id" keyProperty="id">
		insert intoa_demo_dynasty(name, content, stYear, edYear, guoZuo, capital, status, createTime, updateTime, pubTime) 
		values<!-- 如果parameterType是一个pojo,#{pojo的属性名}-->(#{name}, #{content}, #{stYear}, #{edYear}, #{guoZuo}, #{capital}, #{status},#{createTime},#{updateTime},#{pubTime})</insert><!-- 查询多条记录--><select id="findListDao" parameterType="map" resultType="com.jinghangzz.mybatis.data.pojo.ADemoDynasty">
		select* from a_demo_dynasty<where><!-- 按照关键字查询--><if test="keyword != null and keyword != ''">
				and(name like #{keyword} or content like #{keyword})</if><!-- 按照状态查询--><if test="status != null and status != ''">
				and status= #{status}</if><!-- 按照时间范围查询
				如果加上空字符串判断,它本身就已经是一个字符串类型,(传入的是Date类型)--><if test="st != null and ed != null"><![CDATA[ 
					and pubTime>= #{st} and pubTime< #{ed}]]></if></where><!-- 排序--><choose><when test="orderBy == 'idDesc'">
				order by id desc</when><otherwise>
				order by pubTime desc</otherwise></choose></select><!-- 查询一条记录--><select id="findOneDao" parameterType="map" resultType="com.jinghangzz.mybatis.data.pojo.ADemoDynasty">
		select* from a_demo_dynasty<where><choose><when test="id != null and id != ''">
					and id= #{id}</when><when test="name != null and name != ''">
					and name= #{name}</when><otherwise><!-- 如果啥也不传,就查询id为1的记录,不能报错-->
					and id=1</otherwise></choose></where><!-- 排序--><choose><when test="orderBy == 'idDesc'">
				order by id desc</when><otherwise>
				order by pubTime desc</otherwise></choose><!-- 防止报错-->
		limit1;</select><!-- 更新一条记录--><update id="updateOneDao" parameterType="com.jinghangzz.mybatis.data.pojo.ADemoDynasty">
		update a_demo_dynasty<set>
			name= #{name}, content= #{content}, 
			stYear= #{stYear}, edYear= #{edYear}, guoZuo= #{guoZuo}, capital= #{capital}, 
			status= #{status}, createTime= #{createTime}, updateTime= #{updateTime}, 
			pubTime= #{pubTime},</set><where>
			and id= #{id}</where></update><!-- 删除多条记录--><delete id="deleteBatchDao" parameterType="map">
		delete from a_demo_dynasty<where><choose><when test="id != null and id != ''">
					and id= #{id}</when><when test="name != null and name != ''">
					and name= #{name}</when><otherwise><!-- 如果木有传入条件,就删除1条记录-->
					order by pubTime desc
					limit1;</otherwise></choose></where></delete></mapper>

测试代码

import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.ibatis.session.SqlSession;import org.junit.Test;import com.jinghangzz.mybatis.data.dao.IADemoDynastyDao;import com.jinghangzz.mybatis.data.pojo.ADemoDynasty;import com.jinghangzz.mybatis.data.test.BaseTest;/**
 * Dao接口的代理类
 * @author TeaBig
 */publicclassADemoDynastyDaoMapperTestextendsBaseTest{/**
	 * 保存一条记录
	 */@TestpublicvoidsaveOneDao(){/*获取链接
		 * 参数如果为true,就是自动提交
		 * */
		SqlSession session=this.sqlSessionFactory.openSession(true);this.logger.info("session:{}",session);/* 发送sql语句
		 * 参数是:Dao的Class对象(反射)
		 * 	有三种:
		 * 		~对象名.getClass
		 * 		~类名或者接口名.getClass();
		 * 		~Class.forName();
		 * 返回值就是参数的Class对应的类型(对象)
		 *  */
		IADemoDynastyDao demoDynastyDao= session.getMapper(IADemoDynastyDao.class);/* 保存一条记录 */
		ADemoDynasty demoDynasty=newADemoDynasty();/* 木有设置主键的 */
		demoDynasty.setName("东汉");
		demoDynasty.setContent("东汉");
		demoDynasty.setCapital("洛阳");
		demoDynasty.setStYear(24);
		demoDynasty.setEdYear(221);
		demoDynasty.setGuoZuo(167);
		demoDynasty.setCreateTime(newDate());
		demoDynasty.setUpdateTime(newDate());
		demoDynasty.setPubTime(newDate());/* 调用dao的方法 */int res= demoDynastyDao.saveOneDao(demoDynasty);this.logger.info("=返回:{},主键:{}==",res,demoDynasty.getId());/* 关闭链接 */if(session!= null){
			session.close();
			session= null;}}/**
	 * 查询多条记录
	 */@TestpublicvoidfindListDao(){/*获取链接
		 * 参数如果为true,就是自动提交
		 * */
		SqlSession session=this.sqlSessionFactory.openSession(true);this.logger.info("session:{}",session);/* 发送sql语句
		 * 参数是:Dao的Class对象(反射)
		 * 	有三种:
		 * 		~对象名.getClass
		 * 		~类名或者接口名.getClass();
		 * 		~Class.forName();
		 * 返回值就是参数的Class对应的类型(对象)
		 *  */
		IADemoDynastyDao demoDynastyDao= session.getMapper(IADemoDynastyDao.class);
		Map<String, Object> condMap=newHashMap<String, Object>();/* 添加搜索条件 */
		condMap.put("keyword","%清%");
		condMap.put("status","1");
		condMap.put("st",newDate());
		condMap.put("ed",newDate());/* 查询多条记录 */
		List<ADemoDynasty> demoDynastyList= demoDynastyDao.findListDao(condMap);
		demoDynastyList.forEach( t->this.logger.info("数据:{}",t));/* 关闭链接 */if(session!= null){
			session.close();
			session= null;}}/**
	 * 查询多条记录
	 */@TestpublicvoidfindOneDao(){/*获取链接
		 * 参数如果为true,就是自动提交
		 * */
		SqlSession session=this.sqlSessionFactory.openSession(true);this.logger.info("session:{}",session);/* 发送sql语句
		 * 参数是:Dao的Class对象(反射)
		 * 	有三种:
		 * 		~对象名.getClass
		 * 		~类名或者接口名.getClass();
		 * 		~Class.forName();
		 * 返回值就是参数的Class对应的类型(对象)
		 *  */
		IADemoDynastyDao demoDynastyDao= session.getMapper(IADemoDynastyDao.class);
		Map<String, Object> condMap=newHashMap<String, Object>();/* 添加搜索条件 *///condMap.put("id", "3");
		condMap.put("name","大清");/* 查询多条记录 */
		ADemoDynasty demoDynasty= demoDynastyDao.findOneDao(condMap);this.logger.info("数据:{}",demoDynasty);/* 关闭链接 */if(session!= null){
			session.close();
			session= null;}}/**
	 * 查询多条记录
	 */@TestpublicvoidupdateOneDao(){/*获取链接
		 * 参数如果为true,就是自动提交
		 * */
		SqlSession session=this.sqlSessionFactory.openSession(true);this.logger.info("session:{}",session);/* 发送sql语句
		 * 参数是:Dao的Class对象(反射)
		 * 	有三种:
		 * 		~对象名.getClass
		 * 		~类名或者接口名.getClass();
		 * 		~Class.forName();
		 * 返回值就是参数的Class对应的类型(对象)
		 *  */
		IADemoDynastyDao demoDynastyDao= session.getMapper(IADemoDynastyDao.class);
		Map<String, Object> condMap=newHashMap<String, Object>();/* 添加搜索条件 *///condMap.put("id", "3");
		condMap.put("name","大清");/* 查询多条记录 */
		ADemoDynasty demoDynasty= demoDynastyDao.findOneDao(condMap);this.logger.info("数据:{}",demoDynasty);	
		
		demoDynasty.setName(demoDynasty.getName()+"+++++我修改了");/* 以后更新的时候是先查询,再更新 */int res= demoDynastyDao.updateOneDao(demoDynasty);this.logger.info("结果:{},id:{}",res,demoDynasty.getId());/* 关闭链接 */if(session!= null){
			session.close();
			session= null;}}/**
	 * 删除多条记录
	 */@TestpublicvoiddeleteBatchDao(){/*获取链接
		 * 参数如果为true,就是自动提交
		 * */
		SqlSession session=this.sqlSessionFactory.openSession(true);this.logger.info("session:{}",session);/* 发送sql语句
		 * 参数是:Dao的Class对象(反射)
		 * 	有三种:
		 * 		~对象名.getClass
		 * 		~类名或者接口名.getClass();
		 * 		~Class.forName();
		 * 返回值就是参数的Class对应的类型(对象)
		 *  */
		IADemoDynastyDao demoDynastyDao= session.getMapper(IADemoDynastyDao.class);
		Map<String, Object> condMap=newHashMap<String, Object>();/* 添加搜索条件 *///condMap.put("id", "3");
		condMap.put("name","大唐");/* 以后更新的时候是先查询,再更新 */int res= demoDynastyDao.deleteBatchDao(condMap);this.logger.info("结果:{},条件:{}",res,condMap);/* 关闭链接 */if(session!= null){
			session.close();
			session= null;}}}

BaseTest.java

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.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.jinghangzz.mybatis.data.pojo.ADemoDynasty;/**
 * 测试Mybatis的初始化操作
 * @author TeaBig
 */publicclassBaseTest{/*  */protected Logger logger= LogManager.getLogger();/* sqlsessionFactory,让所有的类都能使用 */protected SqlSessionFactory sqlSessionFactory;/**
	 * 初始化
	 */@Beforepublicvoidinit(){/* 读取配置文件;位置是从classpath中读取 */
		String resource="mybatis.cfg.xml";
		InputStream is= null;try{/* 以流的形式读取 */
			is= Resources.getResourceAsStream(resource);/* 构建SqlsessionFactory;
			 * SqlsessionFactory===DriverManager
			 *  */
			sqlSessionFactory=newSqlSessionFactoryBuilder().build(is);this.logger.info("sqlSessionFactory:{}",sqlSessionFactory);}catch(Exception e){this.logger.error("初始化报错了",e);}}/**
	 * 关闭链接
	 */@Afterpublicvoidclose(){/*========= 关闭链接============== */this.logger.info("关闭链接");}/**
	 * 查询多条记录
	 */@TestpublicvoidselectList(){/* 获取链接
		 * SqlSession===Connection;
		 *  */
		SqlSession session= sqlSessionFactory.openSession();this.logger.info("session:{}",session);/*=========以上是加载驱动,获取链接==============*//*=========操作数据库==============*//*
		 * 查询多条:selectList
		 * 查询单条:selectOne
		 * 
		 * 参数1:mapper文件中,namespace(如果sql语句的id在全局中是唯一的,那可以省略namespace)+sql语句的id
		 * *///		List<ADemoDynasty> dynastyList = session.selectList("selectList");
		List<ADemoDynasty> dynastyList= session.selectList("test.selectList");/* 如何循环 */
		dynastyList.forEach( t-> System.out.println("==>"+ t));/* 关闭链接 */
		session.close();}/**
	 * Mybatis的初始化和JDBC的四步走一样;
	 * Mybatis对JDBC四步走做了一个封装
	 */@Testpublicvoidtest(){/* 读取配置文件;位置是从classpath中读取 */
		String resource="mybatis.cfg.xml";
		InputStream is= null;try{/* 以流的形式读取 */
			is= Resources.getResourceAsStream(resource);/* 构建SqlsessionFactory;
			 * SqlsessionFactory===DriverManager
			 *  */
			SqlSessionFactory sqlSessionFactory=newSqlSessionFactoryBuilder().build(is);this<
  • 作者:逆风向上
  • 原文链接:https://blog.csdn.net/qq_45563305/article/details/103348020
    更新时间:2022-08-13 12:47:13