团队开发一个项目,由老大架了一个框架,遇到了DAO层不用写接口了,我也是用了2次才记住这个事的,因为自己一直都是习惯于写DAO层的实现类,所以,习惯性的还是写了个实现类。于是遇到错误了。

找不到那个方法。问了团队的人才知道,方法名和Mapper中配置的id名必须一样。

实现:

一、配置Spring集成MyBatis:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"... ------------------------------------------------- <!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
...
------------------------------------------------- <!-- 产生sqlsessionfactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean> --------------------------------------------------

要实现对数据库的操作必须要有sqlSession,而sqlSession是由sqlSessionFactory创建的。我们可以在spring配置好bean。

<!-- 自动扫描mapper接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="com.xiaojuzi.chaojijuhui.**.dao"
p:sqlSessionFactoryBeanName="sqlSessionFactory" />

这个配置就是配置映射文件的路径,这样做的好处就是不用再写Dao的实现类了,也就是说,我们写好接口,写好配置文件,会自动映射到对应的方法和sql语句。

二、开发mapper.xml映射文件

<mapper namespace="com.xiaojuzi.chaojijuhui.user.dao.UserDao">

-------------------------------------------------------

在这里只有一个UserDao(被代理的接口)。 
user.mapper.xml–namespace配置的就是UserDao的包全名。

三、开发mapper.java的接口

     /**
* 根据用户的用户名查询用户
* @param user
* @return
*/
User queryUserByLoginName (String loginName); /**
* 用户通过手机号码去修改密码
* @param userModel
* @return
*/
Boolean updatePasswordByMobile(UserModel userModel);

如果需要特定类型的参数,就自己再造一个POJO类(例如:UserModel)。

 <sql id="userColumns">
u.id,
u.login_name as "loginName",
u.head_img as "headImg",
...
--------------------------------------------- <select id="queryUserByLoginName" resultType="User" parameterType="User">
SELECT <include refid="userColumns" />
FROM juhui_user u
WHERE u.login_name = #{loginName}
and u.del_flag = #{DEL_FLAG_NORMAL}
</select> <update id="updatePasswordByMobile" parameterType="UserModel">
update juhui_user set
update_date=DATE_FORMAT(#{updateDate}, '%Y-%m-%d %H:%i:%S'),
salt = #{salt},
password = #{password}
where mobile = #{mobile}
</update>

这里mapper.xml的(select、insert、update..)标签的id必须和DAO接口的方法名一样!

Mapper开发规则

1、 在mapper.xml中将namespace设置为mapper.Java的全限定名 
2、 将mapper.java接口的方法名和mapper.xml中statement的id保持一致。 
3、 将mapper.java接口的方法输入参数类型和mapper.xml中statement的parameterType保持一致 
4、 将mapper.java接口的方法输出 结果类型和mapper.xml中statement的resultType保持一致

注意遵循上边四点规范!

这样抛弃Dao实现类的写法: 
具有更好的可扩展性,提高了灵活度。

原理

再根据网上的一些知识点,讲一下原理:

mybatis通过JDK的动态代理方式,在启动加载配置文件时,根据配置mapper的xml去生成Dao的实现。

session.getMapper()使用了代理,当调用一次此方法,都会产生一个代理class的instance,看看这个代理class的实现.

public class MapperProxy implements InvocationHandler {
...
public static <T> T newMapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
ClassLoader classLoader = mapperInterface.getClassLoader();
Class<?>[] interfaces = new Class[]{mapperInterface};
MapperProxy proxy = new MapperProxy(sqlSession);
return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
} public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (!OBJECT_METHODS.contains(method.getName())) {
final Class<?> declaringInterface = findDeclaringInterface(proxy, method);
final MapperMethod mapperMethod = new MapperMethod(declaringInterface, method, sqlSession);
final Object result = mapperMethod.execute(args);
if (result == null && method.getReturnType().isPrimitive()) {
throw new BindingException("Mapper method '" + method.getName() + "' (" + method.getDeclaringClass() + ") attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
return null;
}

这里是用到了JDK的代理Proxy。 newMapperProxy()可以取得实现interfaces 的class的代理类的实例。

当执行interfaces中的方法的时候,会自动执行invoke()方法,其中public Object invoke(Object proxy, Method method, Object[] args)中 method参数就代表你要执行的方法.

MapperMethod类会使用method方法的methodName 和declaringInterface去取 sqlMapxml 取得对应的sql,也就是拿declaringInterface的类全名加上 sql-id..

总结: 
这个就是利用JDK的代理类实现的。

[MyBatis]DAO层只写接口,不用写实现类的更多相关文章

  1. MyBatis Dao层的编写

    传统的dao层编写 以前编写dao层,先新建一个包com.chy.dao,再写接口StudentDao: public interface StudentDao { public void inser ...

  2. MyBatis dao层 方法传参

    MyBatis dao层 方法传参有三种方法. 1. 以下标的方法获取参数. <update id="insertSuccessKilled">       INSER ...

  3. 数据库Dao层编增删改查写,数据库事务,数据库升级

    数据库事务 有两个特点 1.安全性 情景:正常的转账行为,这个时候如果出现停电等异常,已经扣钱但是没有加钱:这个时候就可用数据库事务解决问题 2.高效性: 使用数据库事务添加享受同数量的数据,对比耗时 ...

  4. mybatis dao 层开发简易版 非整合 spring

    同样老习惯,先上项目结构截图 首先 补充上篇文中缺失的 mysql demo 用的 小脚本 drop database if exists mybatis; CREATE DATABASE `myba ...

  5. MyBatis DAO层传递参数到mapping.xml 几种方式

    Dao层传递参数到mapping.xml文件的几种方式:(Mybatis传值总结) 第一种:传递单个参数 Dao层Code片段: /** * 根据articleId查询XXXX详情. * * @par ...

  6. 基于dbunit进行mybatis DAO层Excel单元测试

    DAO层测试难点 可重复性,每次运行单元测试,得到的数据是重复的 独立性,测试数据与实际数据相互独立 数据库中脏数据预处理 不能给数据库中数据带来变化 DAO层测试方法 使用内存数据库,如H2.优点: ...

  7. Mybatis Dao层注解及XML组合Dao的开发方式

    mybatis可以用xml进行数据操作,也可以在dao层用注解的方式,也可以采取xml和dao层接口组合使用的方法.显然 ,后者更加简单. 实体类Student   package com.zhao. ...

  8. 黑马MyBatisday2 MyBatis Dao层实现 接口代理实现&传统实现 动态SQL和SQL抽取 自定义类型处理 分页插件PageHelper

    package com.itheima.mapper; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelp ...

  9. mybatis之DAO层自动实现接口

    * 使用mybatis举例,使用DAO接口方式实现* 不需要针对接口去编写具体的实现类代码,编写映射XML文件,直接拿来使用即可.* 1.导入jar包:mybatis和mysql-connector* ...

随机推荐

  1. python爬虫(7)——BeautifulSoup

    今天介绍一个非常好用的python爬虫库--beautifulsoup4.beautifulsoup4的中文文档参考网址是:http://beautifulsoup.readthedocs.io/zh ...

  2. 安装RabbitMQ(一)

    RabbitMQ简介 RabbitMQ 是由 LShift 提供的一个 Advanced Message Queuing Protocol (AMQP) 的开源实现,由以高性能.健壮以及可伸缩性出名的 ...

  3. Vue.js响应式原理

      写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue.js源码,并做了总结与输出. 文章的原地址:answershuto/learnV ...

  4. vuejs、eggjs全栈式开发设备管理系统

    vuejs.eggjs全栈式开发简单设备管理系统 业余时间用eggjs.vuejs开发了一个设备管理系统,通过mqtt协议上传设备数据至web端实时展现,包含设备参数分析.发送设备报警等模块.收获还是 ...

  5. shell 颜色控制系列

    shell脚本里,经常用的颜色控制,如下 格式:echo -e "\033[字背景颜色:文字颜色m字符串\033[0m" eg:echo -e "\033[41;36m ...

  6. nxlog4go Log Levels and Pattern Layout

    Log levels nxlog4go provides log levels as below: type Level int const ( FINEST Level = iota FINE DE ...

  7. HZAU 1199: Little Red Riding Hood 01背包

    题目链接:1199: Little Red Riding Hood 思路:dp(i)表示前i朵花能取得的最大价值,每一朵花有两种选择,摘与不摘,摘了第i朵花后第i-k到i+k的花全部枯萎,那么摘的话d ...

  8. .net Winfrom 僵尸窗口 的问题

    执行顺序如下: Form1 form1 =new Form1(); form1.ShowDialog(); Form2 form2= Application.OpenForms["Form2 ...

  9. Shell脚本——cat/EOF输出多行

    在某些场合,可能我们需要在脚本中生成一个临时文件,然后把该文件作为最终文件放入目录中.(可参考ntop.spec文件)这样有几个好处,其中之一就是临时文件不是唯一的,可以通过变量赋值,也可根据不同的判 ...

  10. hadoop源码调试

    原文地址:http://www.cnblogs.com/end/archive/2011/04/26/2029497.html 在使用hadoop的时候,可能遇到各种各样的问题,然而由于hadoop的 ...