0


【JAVAEE框架】MyBatis与Spring的整合(上)

哈喽~大家好呀,这篇来看看MyBatis与Spring的整合

🥇个人主页:个人主页​​​​​

🥈 系列专栏:【java框架】

🥉与这篇相关的文章:

一、前言

要在Spring中使用MyBatis,需要在Spring的配置文件中定义一些类
SqlSessionFactoryBean :为整合应用提供SqlSession对象资源
SqlSessionTemplate: 负责管理MyBatis的SqlSession,调用SQL映射语句,实现对数据库的访问
MapperFactoryBean: 根据指定Mapper接口生成Bean实例
MapperScannerConfigurer: 根据指定包批量扫描Mapper接口并生成实例

Spring和MyBatis的整合步骤

1、建立Web工程,加入Spring和MyBatis的有关JAR
2、建立开发目录结构,创建实体类
3、创建数据访问接口
4、创建数据访问接口的实现类
5、配置SQL映射语句文件
6、配置MyBatis应用配置文件
7、配置Spring应用配置文件

采用数据映射器(MapperFactoryBean)的方式完成对数据库操作
根据Mapper接口获取Mapper对象,它封装了原有的SqlSession.getMapper()功能的实现

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="cn.smbms.dao.user.UserMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

注:映射器对应的SQL映射文件与映射器的类路径相同,该映射文件可以自动被MapperFactoryBean解析

无奖问答:若映射器很多的话,相应的配置项也会很多,如何简化配置工作量?

MapperScannerConfigurer
自动扫描指定包下的Mapper接口,并将它们直接注册为MapperFactoryBean

MapperScannerConfigurer递归扫描基准包下所有接口,若它们在SQL映射文件中定义过,则动态注册为MapperFactoryBean,如此即可批量产生映射器实现类

二、原生代码展示

我们这里使用的是德鲁伊(druid)连接池

导入pom 文件

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

mybatis-config.xml

之前讲过,这里就不多讲了,可以看看mybatis起步的那片文章

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 配置文件的根元素 -->
<configuration>

    <!--设置:定义mybatis的一些全局属性-->
    <!--jdbcTypeForNull:当添加数据的时候,部分字段为null时,自动填入null,不加配置则会报错-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
        <!--PARTIAL[默认],FULL[全匹配],NONE[不匹配]-->
        <setting name="autoMappingBehavior" value="FULL"/>
        <setting name="jdbcTypeForNull" value="NULL"/>
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <!--配置别名-->
    <typeAliases>
        <package name="com.itxzw.user.model"/>
    </typeAliases>

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <property name="helperDialect" value="mysql"/>
        </plugin>
    </plugins>

</configuration>

jdbc.properties 配置文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
username=root
password=123456

initialSize=8

maxActive=20

maxWait=300
maxIdle=50
minIdle=3

applicationContext.xml

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

<!--    引入外部文件-->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="jdbc.properties"/>
    </bean>

<!--    配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
        <property name="initialSize" value="${initialSize}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="maxWait" value="${maxWait}"/>
        <property name="minIdle" value="${minIdle}"/>
        <property name="maxIdle" value="${maxIdle}"/>
    </bean>

<!--    创建 SqlSessionFactoryBean -->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="mybatis-config.xml"/>
        <property name="mapperLocations">
            <list>
                <value>com/itxzw/*/dao/mapper/*.xml</value>
            </list>
        </property>
    </bean>

    <!--    创建 sqlSessionTemplate -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="factory"/>
    </bean>

<!--    创建 dao 和 service bean-->
    <bean id="userDao" class="com.itxzw.user.dao.impl.UserDao">
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>

    <bean id="UserService" class="com.itxzw.user.service.Impl.UserService">
        <property name="userDao" ref="userDao"/>
    </bean>

</beans>

PageModel 数据分页配置

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class PageModel<T> {

    private int pageNum;  // 当前页数
    private int pageSize; // 每页显示条数
    private int totalPage; // 总页数
    private long totalRows; // 总条数
    private List<T> data;

}

IUserDao 接口

public interface IUserDao {

    public List<SmbmsUser> getUserListByCondition(UserCondition conn);

    public int updateUser(SmbmsUser user);

    // 1,3,11
    public int deleteUser(String ids);

    public int addUser(SmbmsUser user);

}

实现类 UserDao

public class UserDao implements IUserDao {

    private String namespace = "com.itxzw.user.dao.IUserDao";

    private SqlSessionTemplate sqlSession;

    public SqlSessionTemplate getSqlSession() {
        return sqlSession;
    }

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<SmbmsUser> getUserListByCondition(UserCondition conn) {
        return sqlSession.selectList(namespace + ".getUserListByCondition", conn);
    }

    @Override
    public int updateUser(SmbmsUser user) {
        return sqlSession.update(namespace + ".updateUser", user);
    }

    @Override
    public int deleteUser(String ids) {
        return sqlSession.update(namespace + ".deleteUser", ids);
    }

    @Override
    public int addUser(SmbmsUser user) {
        return sqlSession.update(namespace + ".addUser", user);
    }
}

mapper

<mapper namespace="com.itxzw.user.dao.IUserDao">

    <cache eviction="FIFO" flushInterval="60000" readOnly="true" />

    <resultMap id="smbmsUser" type="smbmsUser">
        <id property="id" column="id"></id>
    </resultMap>

    <select id="getUserListByCondition" parameterType="userCondition"  resultMap="smbmsUser">
        <![CDATA[
            select
                u.ID,
                u.USERCODE,
                u.USERNAME,
                u.USERPASSWORD,
                u.GENDER,
                u.BIRTHDAY,
                u.PHONE,
                u.ADDRESS,
                u.userrole,
                u.CREATEDBY,
                u.CREATIONDATE,
                u.MODIFYBY,
                u.MODIFYDATE
            from SMBMS_USER u

        ]]>

        <where>
            <if test="id!=null and id!=''">
                <![CDATA[ and id = #{id} ]]>
            </if>
            <if test="un!=null and un!=''">
                <!--<![CDATA[   and username like '%'||#{username}||'%' ]]>-->
                <![CDATA[ and username like '%${un}%' ]]>
            </if>
        </where>

    </select>

    <update id="updateUser" parameterType="smbmsUser">
        <![CDATA[
            update SMBMS_USER set
                usercode = #{usercode},
                username = #{username},
                userpassword = #{userpassword},
                gender = #{gender},
                birthday = #{birthday},
                phone = #{phone},
                address = #{address},
                userrole = #{userrole},
                modifyby = #{modifyby},
                modifydate = #{modifydate}
            where id = #{id}
        ]]>
    </update>

    <!--#{}:占位符,预编译-->
    <!--${}:sql拼接-->

    <delete id="deleteUser" parameterType="string">
        delete from SMBMS_USER
        where id in (${ids})
    </delete>

    <insert id="addUser" parameterType="smbmsUser">
        <![CDATA[
            insert into SMBMS_USER
            (ID,USERCODE,USERNAME,USERPASSWORD,GENDER,BIRTHDAY,PHONE,ADDRESS,USERROLE,CREATEDBY,CREATIONDATE)
            values
            (#{id},#{usercode},#{username},#{userpassword},#{gender},#{birthday},#{phone},#{address},#{userrole},#{createdby},#{creationdate})
        ]]>
    </insert>
</mapper>

实体类 SmbmsUser 与 UserCondition

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class SmbmsUser {

    private String id;
    private String usercode;
    private String username;
    private String userpassword;
    private long gender;
    private Date birthday;
    private String phone;
    private String address;
    private String userrole;
    private String createdby;
    private Date creationdate;
    private String modifyby;
    private Date modifydate;

}
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class UserCondition {
    private String id;
    private String usercode;
    private String un;
    private String gender;
    private String userrole;
    private String createdby;

}

IUserService接口 与 实现类 UserService

public interface IUserService {

    public List<SmbmsUser> getUserListByCondition(UserCondition conn);

    public PageModel<SmbmsUser> getUserListByCondition(UserCondition conn, PageModel<SmbmsUser> pageModel);

    public int updateUser(SmbmsUser user);

    public int deleteUser(String ids);

    public int addUser(SmbmsUser user);

}
public class UserService implements IUserService {

    private IUserDao userDao;

    public IUserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public List<SmbmsUser> getUserListByCondition(UserCondition conn) {
        return userDao.getUserListByCondition(conn);
    }

    @Override
    public PageModel<SmbmsUser> getUserListByCondition(UserCondition conn, PageModel<SmbmsUser> pageModel) {

        PageHelper.startPage(pageModel.getPageNum(), pageModel.getPageSize());
        List<SmbmsUser> userList = userDao.getUserListByCondition(conn);
        PageInfo<SmbmsUser> pageInfo = new PageInfo<>(userList);

        pageModel.setData(userList);
        pageModel.setTotalPage(pageInfo.getPages());
        pageModel.setTotalRows(pageInfo.getSize());

        return pageModel;
    }

    @Override
    public int updateUser(SmbmsUser user) {
        return userDao.updateUser(user);
    }

    @Override
    public int deleteUser(String ids) {
        return userDao.deleteUser(ids);
    }

    @Override
    public int addUser(SmbmsUser user) {
        return userDao.addUser(user);
    }
}

测试

查询全部

    @Test
    public void test01(){

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        IUserService userService = context.getBean(IUserService.class);

        UserCondition conn = new UserCondition();

        List<SmbmsUser> userList = userService.getUserListByCondition(conn);

        for (SmbmsUser user : userList) {
            System.out.println(user);
        }

    }

插入数据

    @Test
    public void test02(){

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        IUserService userService = context.getBean(IUserService.class);

        SmbmsUser smbmsUser = new SmbmsUser("27","12","张四","123123",12,new Date(),"123","江西","普通用户", "12", new Date(), "12",null);

        int userList = userService.addUser(smbmsUser);

        System.out.println(userList);

    }

删除数据

    @Test
    public void test03(){

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        IUserService userService = context.getBean(IUserService.class);

        int userList = userService.deleteUser("21");

        System.out.println(userList);

    }

分页

    @Test
    public void test05(){

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        IUserService userService = context.getBean(IUserService.class);

        UserCondition conn = new UserCondition();

        PageModel<SmbmsUser> pageModel = new PageModel<>();

        pageModel.setPageNum(1);
        pageModel.setPageSize(5);

        pageModel = userService.getUserListByCondition(conn, pageModel);

        System.out.println(pageModel);

    }

不积跬步无以至千里,趁年轻,使劲拼,给未来的自己一个交代!向着明天更好的自己前进吧!

标签: mybatis spring java-ee

本文转载自: https://blog.csdn.net/aasd23/article/details/127166622
版权归原作者 程序猿追 所有, 如有侵权,请联系我们删除。

“【JAVAEE框架】MyBatis与Spring的整合(上)”的评论:

还没有评论