[MyBatis]DAO层只写接口,不用写实现类
团队开发一个项目,由老大架了一个框架,遇到了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层只写接口,不用写实现类的更多相关文章
- MyBatis Dao层的编写
传统的dao层编写 以前编写dao层,先新建一个包com.chy.dao,再写接口StudentDao: public interface StudentDao { public void inser ...
- MyBatis dao层 方法传参
MyBatis dao层 方法传参有三种方法. 1. 以下标的方法获取参数. <update id="insertSuccessKilled"> INSER ...
- 数据库Dao层编增删改查写,数据库事务,数据库升级
数据库事务 有两个特点 1.安全性 情景:正常的转账行为,这个时候如果出现停电等异常,已经扣钱但是没有加钱:这个时候就可用数据库事务解决问题 2.高效性: 使用数据库事务添加享受同数量的数据,对比耗时 ...
- mybatis dao 层开发简易版 非整合 spring
同样老习惯,先上项目结构截图 首先 补充上篇文中缺失的 mysql demo 用的 小脚本 drop database if exists mybatis; CREATE DATABASE `myba ...
- MyBatis DAO层传递参数到mapping.xml 几种方式
Dao层传递参数到mapping.xml文件的几种方式:(Mybatis传值总结) 第一种:传递单个参数 Dao层Code片段: /** * 根据articleId查询XXXX详情. * * @par ...
- 基于dbunit进行mybatis DAO层Excel单元测试
DAO层测试难点 可重复性,每次运行单元测试,得到的数据是重复的 独立性,测试数据与实际数据相互独立 数据库中脏数据预处理 不能给数据库中数据带来变化 DAO层测试方法 使用内存数据库,如H2.优点: ...
- Mybatis Dao层注解及XML组合Dao的开发方式
mybatis可以用xml进行数据操作,也可以在dao层用注解的方式,也可以采取xml和dao层接口组合使用的方法.显然 ,后者更加简单. 实体类Student package com.zhao. ...
- 黑马MyBatisday2 MyBatis Dao层实现 接口代理实现&传统实现 动态SQL和SQL抽取 自定义类型处理 分页插件PageHelper
package com.itheima.mapper; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelp ...
- mybatis之DAO层自动实现接口
* 使用mybatis举例,使用DAO接口方式实现* 不需要针对接口去编写具体的实现类代码,编写映射XML文件,直接拿来使用即可.* 1.导入jar包:mybatis和mysql-connector* ...
随机推荐
- 如何解决JavaScript中0.1+0.2不等于0.3
console.log(0.1+0.2===0.3)// true or false?? 在正常的数学逻辑思维中,0.1+0.2=0.3这个逻辑是正确的,但是在JavaScript中0.1+0.2!= ...
- Flink入门使用
完全参考:Flink1.3QuickStart 启动本地运行 首先找一台安装了hadoop的linux. 将安装包解压,到bin目录启动local模式的脚本. tar -zxvf flink-1.3. ...
- xBIM WeXplorer xViewer 浏览器检查
目录 基础 xBIM WeXplorer 简要介绍 xBIM WeXplorer xViewer 基本应用 xBIM WeXplorer xViewer 浏览器检查 xBIM WeXplorer xV ...
- IDEA Default模式下的常用快捷键
功 能 快 捷 键 备 注 Back Up Ctr + Alt + Left Forword Ctr + Alt + Right Previous Tab Alt + Left Next Tab Al ...
- MySQL复制同一个服务器的表结构和表数据
例如,现在服务器上有数据库 dbx 和 dby,dbx中有很多表,要把dbx中的表全部复制到dby,如下操作: 首先: use dby; [复制表结构] CREATE TABLE user LIKE ...
- 安装php的memcached模块和扩展支持sasl
memcached的1.2.4及以上增加了CAS(Check and Set)协议,对于同一key的多进行程的并发处理问题.这种情况其实根数据库很像,如果同时有几个进程对同一个表的同一数据进行更新的话 ...
- angular2^ typescript 将 文件和Json数据 合并发送到服务器(2.服务端)
nodejs 中使用框架 express web框架 multer 文件接受 直接贴代码了,我就不解释了 "use strict"; exports.__esModule = tr ...
- 通过读取配置文件,启动mongodb
在实际的项目中,经常利用mongodb数据库做缓存,mongodb的并发性比较高,所以对于快速存储.读取信息有很多优点.在项目中对于第一次的数据请求会直接访问数据库,而对于获得的信息通常都会在此时刻存 ...
- appium+Python 启动app(三)登录
我们根据前面的知识点,用uiautomatorviewer工具来获取我们当前的元素 (注:uiautomatorviewer 是 android sdk 自带的) 知识点:appium的webdriv ...
- 💈 A Cross-Thread Call Helper Class
Conmajia © 2012, 2018 Introduction When you are working on background threads and call frontend GUI ...