spring整合mybatis实现无须编写Mapper的DAO接口类

一般开发中,我们使用mybatis执行SQL语句的时候,经常需要自定义实体类来映射数据库表,同时还要每个映射配置文件(mapper.xml)都要单独写一个DAO接口类和DAO接口实现类,这样会耗费程序员时间去编写代码。为方便日后开发,我们可以直接用hashmap来取代自定义实体类(当然前提条件是开发人员需要对数据库表结构十分熟悉),同时我们可以编写一个公共DAO类实现对所有表的增删改查,就可以节省开发时间。

1.在IoC容器中配置SqlSessionFactory
(这里有一点值得推荐的地方:配置List标签,即可自动扫描所有Mapper.xml,即classpath:com/web/mapper/*.xml)

<!-- 获得sqlSessionFactory -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <!-- 映射数据源 -->
  <property name="dataSource" ref="comboPooledDataSource"/>
  <!-- 映射mybatis核心配置文件 mybatis配置可写可不写,因为这次不用自定义实体类及引入mapper.xml-->
  <property name="configLocation" value="classpath:mybatis-config.xml"/>
  <!-- 映射mapper文件 里加入  mapperLocations  项 即可"自动扫描"目录下所有xml映射文件-->
  <property name="mapperLocations">
   <list>
    <value>classpath:com/web/mapper/*.xml</value>
   </list>
  </property>
 </bean>

2.配置SqlSessionTemplate(可以不用通过工厂获得SQL会话)

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
      <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

3.配置公共DAO类,实现无须编写Mapper的接口类

<bean id="commDAO" class="com.web.dao.CommDAO"></bean>

4.编写公共DAO类

package com.web.dao;
import java.util.Map;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class CommDAO {
 @Autowired
 SqlSessionTemplate template;
 public Map<String,Object> selectOne(String statement,Map<String,Object> map){
  return template.selectOne(statement,map);
 }
}

5.编写UserMapper.xml

<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="UserMapper">
 <select id="getUser" resultType="hashmap" parameterType="hashmap">
  SELECT * FROM temp_test_20200821
  <where>
   pid = #{pid}
   <if test="content!=null and content != '' ">
     AND content =#{content}
   </if>
  </where> 
 </select>
</mapper>

6.在业务类中使用公共DAO类进行查询

//使用mybatis执行SQL语句
  Map<String,Object> inMap = new HashMap<String,Object>();
  inMap.put("pid", 8);
  Map<String,Object> outMap = commDAO.selectOne("UserMapper.getUser",inMap);

7.运行业务类,将结果输出到控制台中,达到预期

for(Entry<String,Object> entry : outMap.entrySet()){
   System.out.println(entry.getKey()+"="+entry.getValue());
  }
CONTENT=mybatis测试
PID=8
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值