一般开发中,我们使用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
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐