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 into a_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>
<!-- 防止报错 -->
limit 1 ;
</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
limit 1 ;
</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
*/
public class ADemoDynastyDaoMapperTest extends BaseTest
{
/**
* 保存一条记录
*/
@Test
public void saveOneDao()
{
/*获取链接
* 参数如果为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 = new ADemoDynasty();
/* 木有设置主键的 */
demoDynasty.setName("东汉");
demoDynasty.setContent("东汉");
demoDynasty.setCapital("洛阳");
demoDynasty.setStYear(24);
demoDynasty.setEdYear(221);
demoDynasty.setGuoZuo(167);
demoDynasty.setCreateTime(new Date());
demoDynasty.setUpdateTime(new Date());
demoDynasty.setPubTime(new Date());
/* 调用dao的方法 */
int res = demoDynastyDao.saveOneDao(demoDynasty);
this.logger.info("=返回:{},主键:{}==",res,demoDynasty.getId());
/* 关闭链接 */
if(session != null )
{
session.close();
session = null ;
}
}
/**
* 查询多条记录
*/
@Test
public void findListDao()
{
/*获取链接
* 参数如果为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 = new HashMap<String, Object>();
/* 添加搜索条件 */
condMap.put("keyword", "%清%");
condMap.put("status", "1");
condMap.put("st", new Date());
condMap.put("ed", new Date());
/* 查询多条记录 */
List<ADemoDynasty> demoDynastyList = demoDynastyDao.findListDao(condMap);
demoDynastyList.forEach( t -> this.logger.info("数据:{}",t));
/* 关闭链接 */
if(session != null )
{
session.close();
session = null ;
}
}
/**
* 查询多条记录
*/
@Test
public void findOneDao()
{
/*获取链接
* 参数如果为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 = new HashMap<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 ;
}
}
/**
* 查询多条记录
*/
@Test
public void updateOneDao()
{
/*获取链接
* 参数如果为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 = new HashMap<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 ;
}
}
/**
* 删除多条记录
*/
@Test
public void deleteBatchDao()
{
/*获取链接
* 参数如果为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 = new HashMap<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
*/
public class BaseTest
{
/* */
protected Logger logger = LogManager.getLogger() ;
/* sqlsessionFactory,让所有的类都能使用 */
protected SqlSessionFactory sqlSessionFactory ;
/**
* 初始化
*/
@Before
public void init()
{
/* 读取配置文件;位置是从classpath中读取 */
String resource = "mybatis.cfg.xml";
InputStream is = null ;
try
{
/* 以流的形式读取 */
is = Resources.getResourceAsStream(resource);
/* 构建SqlsessionFactory;
* SqlsessionFactory===DriverManager
* */
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
this.logger.info("sqlSessionFactory:{}",sqlSessionFactory);
} catch (Exception e)
{
this.logger.error("初始化报错了",e);
}
}
/**
* 关闭链接
*/
@After
public void close()
{
/*========= 关闭链接============== */
this.logger.info("关闭链接");
}
/**
* 查询多条记录
*/
@Test
public void selectList()
{
/* 获取链接
* 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四步走做了一个封装
*/
@Test
public void test()
{
/* 读取配置文件;位置是从classpath中读取 */
String resource = "mybatis.cfg.xml";
InputStream is = null ;
try
{
/* 以流的形式读取 */
is = Resources.getResourceAsStream(resource);
/* 构建SqlsessionFactory;
* SqlsessionFactory===DriverManager
* */
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
this.logger.info("sqlSessionFactory:{}",sqlSessionFactory);
/* 获取链接
* 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");
/* 如何循环 */
dynastyList.forEach( t -> System.out.println("==>" + t));
/*========= 关闭链接============== */
session.close();
} catch (Exception e)
{
this.logger.error("报错了",e);
} finally
{
try
{
if(is != null)
{
is.close();
is = null ;
}
} catch (IOException e)
{
this.logger.error("关闭出错了",e);
}
}
}
}
dao.java
import java.util.List;
import java.util.Map;
import com.jinghangzz.mybatis.data.pojo.ADemoDynasty;
/**
* Dao:Data Access Object
* 接口强烈建议,以I开头()Interface
* @author TeaBig
*/
public interface IADemoDynastyDao
{
/**
* 保存一条记录,
* @param demoDynasty pojo对象(Domain,Entity)
* @return 此条sql语句操作数据库影响的条数
*/
int saveOneDao(ADemoDynasty demoDynasty);
/**
* 更新一条记录
* @param demoDynasty
* @return
*/
int updateOneDao(ADemoDynasty demoDynasty);
/**
* 删除dao,批量操作
* @return
*/
int deleteBatchDao(Map<String, Object> condMap);
/**
* 查询一条记录;
* ~可以根据id查询(唯一)
* ~也可以根据其它的唯一字段查询
* @return
*/
ADemoDynasty findOneDao(Map<String, Object> condMap);
/**
* 查询多条记录
* ~根据关键字查询
* ~根据状态查询
* ~根据时间查询
* @param condMap
* @return
*/
List<ADemoDynasty> findListDao(Map<String, Object> condMap);
}
pojo.java
import java.util.Date;
/**
* 朝代的POJO
* pojo的类名和表名一样(把_去掉,注意驼峰标识)
* pojo的属性名和表的类名一样
* pojo的对象和表的记录一样;
* @author TeaBig
*/
public class ADemoDynasty
{
private int id;
private String name;
private String content;
private int stYear;
private int edYear;
private int guoZuo;
private String capital;
private byte status;
private Date createTime;
private Date updateTime;
private Date pubTime;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
public int getStYear()
{
return stYear;
}
public void setStYear(int stYear)
{
this.stYear = stYear;
}
public int getEdYear()
{
return edYear;
}
public void setEdYear(int edYear)
{
this.edYear = edYear;
}
public int getGuoZuo()
{
return guoZuo;
}
public void setGuoZuo(int guoZuo)
{
this.guoZuo = guoZuo;
}
public String getCapital()
{
return capital;
}
public void setCapital(String capital)
{
this.capital = capital;
}
public byte getStatus()
{
return status;
}
public void setStatus(byte status)
{
this.status = status;
}
public Date getCreateTime()
{
return createTime;
}
public void setCreateTime(Date createTime)
{
this.createTime = createTime;
}
public Date getUpdateTime()
{
return updateTime;
}
public void setUpdateTime(Date updateTime)
{
this.updateTime = updateTime;
}
public Date getPubTime()
{
return pubTime;
}
public void setPubTime(Date pubTime)
{
this.pubTime = pubTime;
}
@Override
public String toString()
{
return "ADemoDynasty [id=" + id + ", name=" + name + ", content=" + content + ", stYear=" + stYear + ", edYear="
+ edYear + ", guoZuo=" + guoZuo + ", capital=" + capital + ", status=" + status + ", createTime="
+ createTime + ", updateTime=" + updateTime + ", pubTime=" + pubTime + "]";
}
}