java架构经验分享

关于Spring整合Mybatis,这一篇应该算是讲的很清楚了,

2021-05-14  本文已影响0人  程序员匡胤

基本介绍

所谓的Spring整合Mybatis其实说白了就是将mybatis的加载过程全权交给Spring托管,不再需要加载配置工具等一些操作,而具体的dao层操作依旧是使用mybatis去操作数据库。

mybatis使用步骤:

Java基础知识大全

22本Java架构师核心书籍

从0到1Java学习路线和资料

1000+道2021年最新面试题

Spring整合mybatis步骤:

mybatis核心配置

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- 开启日志 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!-- 开启二级缓存 -->
        <setting name="cacheEnabled" value="true"/>
        <!-- 将经典的SQL字段映射为Java驼峰命名变量-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- 别名 -->
    <typeAliases>
        <typeAlias type="com.pojo.User" alias="User"/>
    </typeAliases>
    
    <!-- 映射注册 -->
    <mappers>
        <mapper class="com.dao.UserMapper"/>
    </mappers>

</configuration>

Spring核心配置

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="com.dao"/>
    <context:annotation-config/>

    <!-- 1.将mybatis配置环境集成到spring中,交由Spring托管 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!-- 2. 将SqlSessionFactory交给Spring托管   -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" scope="singleton">
        <property name="dataSource" ref="dataSource"/>          <!-- 加载数据环境   -->
        <!--  绑定mybatis配置文件     -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--   几乎所有的东西都能在这里面配,完全不需要mybatis的核心配置
               根据个人喜好,个人感觉分开一点维护比较容易
        -->
    </bean>

    <!--  3. 将SqlSession对象的加载交给Spring托管  -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!-- 按照mybatis的习俗,通过工厂获得SqlSession会话对象       -->
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

数据库与对应的POJO实体类

package com.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {

    private int id;
    private String username;
    private String password;
    
}

dao层

UserMapper接口

package com.dao;

import com.pojo.User;
import java.util.List;

public interface UserMapper {

    public List<User> getUserList();

}

UserMapper.xml配置

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.UserMapper">

    <!-- 解决字段-属性不匹配问题 -->   
    <resultMap id="map" type="User">
        <id column="id" property="id"/>
        <id column="name" property="username"/>
        <id column="pwd" property="password"/>
    </resultMap>
    <select id="getUserList" resultMap="map">
        select *from user;
    </select>

</mapper>

接口实现类(一)

单独使用mybatis时是不需要这个实现类的,将impl实现类做的操作数据库事情移交到service层执行。而现在需要这个实现类,内部聚合SqlSessionTemplate对象(等价于SqlSession),然后在实现方法中通过反射获取mapper,然后执行SQL即可!

import com.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("userMapperImpl")
public class UserMapperImpl implements UserMapper{

    @Autowired
    private SqlSessionTemplate sqlSession;
    @Override
    public List<User> getUserList() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = mapper.getUserList();
        return list;
    }
}

接口实现类(二)

在Spring - Mybatis最新的整合中提供了SqlSessionDaoSupport抽象类来取代内部聚合SqlSessionTemplate对象,只需要继承这个类即可。虽然明面上不需要依赖注入,但是父类是需要依赖注入一个SqlSessionFactory工厂的!

import com.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> getUserList() {
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = mapper.getUserList();
        return list;
    }
}

测试

@Test
public void test1(){
    ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
    UserMapper userMapperImpl = context.getBean("userMapperImpl", UserMapper.class);
    List<User> list = userMapperImpl.getUserList();
    for (User user : list) {
        System.out.println(user.toString());
    }
}

最后

既然都看到这里了,觉得文章对你有帮助的话记得点个赞!

上一篇下一篇

猜你喜欢

热点阅读