【MyBatis】Dao接口和Dao.xml文件如何建立连接

【MyBatis】Dao接口和Dao.xml文件如何建立连接

问题描述 在编写SSM框架的程序过程中,我们都知道有一个Dao层来建立与SQL的连接,但是,Dao层的接口里面并没有实现类。
如代码所示:

public interface DepartmentDao { 
    public List<Department> search();
    public Department searchById(Integer id);
    public int add(Department dep);
    public int update(Department dep);
    public int delete(int id);
}

那么,问题来了
在我们调用Dao接口的时候是怎么通过Dao.xml文件和SQL建立联系的呢?

1.首先在程序运行开始时,MyBatis会检查配置文件Dao.xml,对文件进行解析,通过mapper标签对dao接口进行一对一的映射(namespace保持唯一)

<mapper namespace="com.alan.hrsys.dao.DepartmentDao">

2.再扫描xml文件其余的部分,xml文件的每个具体操作都通过id和Dao接口的操作名进行对应。相当于Dao接口是领导,告诉xml小弟,我要实现个莫子功能,然后xml具体和数据库对接操作。

Dao接口给出的功能

public List<Department> search();

Dao.xml使用SQL语句具体实现接口给出的功能

<!--配置数据库查找映射	,连接到实体类-->
	<select id="search" resultType="com.alan.hrsys.entity.Department">
		select * from department
	</select>

3.使用Dao接口进行代理
在设计模式中我们学到过,代理模式是代码之间解耦合的一种方式,具体内容打个比方,相当于领导(具体实现类)和秘书的关系。秘书一般坐在领导门外的办公桌上。当有事务需要领导处理时,首先需要进办公室的门(即接口)向秘书(代理类)汇报,秘书就可以对事务进行预处理(方便领导),过滤(如果找错领导了就不让小事打扰领导),转发(经过秘书前期处理后发现确实需要领导拍板,就把报告给领导批示),实现类实现后的后续操作(领导审批完之后再交给秘书去交接)
《【MyBatis】Dao接口和Dao.xml文件如何建立连接》

如何使用Dao接口代理呢?

  • 在Spring.xml文件里面进行配置,对存放有Dao接口的包进行扫描
    《【MyBatis】Dao接口和Dao.xml文件如何建立连接》
 <!-- mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.alan.hrsys.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
  • 将 value=”com.alan.hrsys.dao”路径底下(即Dao接口)全部扫描注册成Java Bean,并且将Bean class设置为MapperFactoryBean。
    (作用)在业务(service)层使用@Autowires注入Dao接口时返回getObject()对象,即通过代理模式,使用Dao接口后调用了Dao .xml文件中的具体实现类。
    代码如下
@Service
public class DepartmentServiceImpl implements DepartmentService { 

	@Autowired
	DepartmentDao depDao;
	@Autowired
	EmployeeDao empDao;

	@Override
	public List<Department> search() { 
		List<Department> list = depDao.search();
		return list;
	}

	@Override
	public Department searchById(Integer id) { 
		Department dep = depDao.searchById(id);
		return dep;
	}

	@Override
	public boolean add(Department dep) { 
		int rs = depDao.add(dep);
		return rs > 0;
	}

	@Override
	public boolean update(Department dep) { 
		int rs = depDao.update(dep);
		return rs > 0;
	}

	@Override
	public boolean delete(Integer id) { 
		int rs = depDao.delete(id);
		rs = empDao.updateByDep(id);
		return rs > 0;
	}

}

总结
当我们在业务层调用Dao接口时,实际上调用的时invoke方法,再通过

<mapper namespace="com.alan.hrsys.dao.DepartmentDao">

找到被代理的实现类,即DepartmentDao.xml文件,就可以对SQL语句进行愉快的操作啦~~

    原文作者:猿蛋蛋
    原文地址: https://blog.csdn.net/weixin_45156425/article/details/120956070
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞