spring使用xml配置方式整合Druid数据源和mybatis(包括分页插件)

时间:2024-10-24 07:08:15

1. 必要依赖

		<!--mysql依赖-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.3.0</version>
        </dependency>

        <!-- druid连接池依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.23</version>
        </dependency>
		
		<!--spring依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.1.12</version>
        </dependency>

		<!--spring操作jdc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.1.12</version>
        </dependency>
		
		<!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.16</version>
        </dependency>
        <!-- spring整合mybatis依赖插件,
        	由于spirng没有提供对应的依赖进行整合,所以需要用到该依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>3.0.4</version>
        </dependency>
        <!-- 分页插件依赖 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>6.1.0</version>
        </dependency>
		<!--lombox依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.32</version>
        </dependency>

2.在resources创建xml配置文件(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:mybatis="http://mybatis.org/schema/mybatis-spring"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">



    <!-- 整合Druid数据源连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 注入相关的连接属性 -->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/demo?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;timeZone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
        <!-- 连接池的属性配置-->
        <!-- 最大连接池数量-->
        <property name="maxActive" value="200"/>
        <!-- 初始化连接池的时候建立的连接个数-->
        <property name="initialSize" value="10"/>
        <!-- 连接池最小连接数-->
        <property name="minIdle" value="10"/>
        <!-- 获取连接的最大等待时间,单位:毫秒-->
        <property name="maxWait" value="2000"/>
        <!-- 检测连接是否有效-->
        <property name="testWhileIdle" value="true"/>
        <property name="testOnReturn" value="false"/>
        <!-- 用一条伪sql来检查连接-->
        <property name="validationQuery" value="select 1"/>
        <!-- 是否缓存PreparedStatement,mysql中建议关闭-->
        <property name="poolPreparedStatements" value="false"/>
    </bean>

    <!-- 整合mybatis, 目的就是将SqlSessionFactory纳入IOC容器,
    SqlSessionFactoryBean实现了Spring的FactoryBean接口,这样spring
    容器就可以通过接口的getObject方法得到SqlSessionFactory并纳入容器中
    -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 实体类的别名-->
        <property name="typeAliasesPackage" value="edu.nf.ch02.entity"/>
        <!-- 指定mapper映射配置文件的路径-->
        <property name="mapperLocations" value="classpath:mappers/*.xml"/>
        <!-- 配置分页插件-->
        <property name="plugins">
            <!-- 分页插件也作为一个Bean纳入容器 -->
            <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                    <props>
                        <!-- 数据库方言 -->
                        <prop key="helperDialect">mysql</prop>
                        <!-- 启用分页参数注解-->
                        <prop key="supportMethodsArguments">true</prop>
                        <!-- 分页合理化-->
                        <prop key="reasonable">true</prop>
                    </props>
                </property>
            </bean>
        </property>
    </bean>
    <!-- 指定扫描的dao接口,这样就会基于动态代理在运行时创建Dao接口的代理实现,
     这个代理实现也会自动纳入Spring容器-->
    <mybatis:scan base-package="edu.nf.ch02.dao"/>
    <!-- 扫描包 -->
    <context:component-scan base-package="edu.nf.ch02"/>
</beans>

3. 创建City实体类

@Data
public class City {
    private Integer cityId;
    private String cityName;
    private String cityCode;
    private String province;
}

4. 创建service接口(CityService)和实现类(CityServiceImpl)

cityService接口

/**
 * service接口
 */
public interface CityService {

    /**
     * 查询城市列表
     * @param pageNum
     * @param pageSize
     * @param province
     * @return
     */
    PageInfo<City> listCity(int pageNum, int pageSize, String province);
}

cityServiceImpl实现类

/**
 * cityService实现类
 */
@Service("cityService")
@RequiredArgsConstructor
public class CityServiceImpl implements CityService {

    /**
     * 构造方法注入dao
     */
    private final CityDao cityDao;

    @Override
    public PageInfo<City> listCity(int pageNum, int pageSize, String province) {
        List<City> list = cityDao.listCity(pageNum, pageSize, province);
        return new PageInfo<>(list);
    }
}

5. 创建cityDao接口

/**
 * cityDao接口
 */
public interface CityDao {

    /**
     * 查询城市列表
     * @param pageNum
     * @param pageSize
     * @param province
     * @return
     */
    List<City> listCity(@Param("pageNum") Integer pageNum,
                        @Param("pageSize") Integer pageSize,
                        @Param("province") String province);
}

6. 在resources目录下创建mappers文件,在到mappers中创建CityDao映射的xml文件(CityDaoMapper.xml)

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.nf.ch02.dao.CityDao">
    <resultMap id="cityMap" type="edu.nf.ch02.entity.City">
        <id property="cityId" column="city_id"/>
        <result property="cityName" column="city_name"/>
        <result property="cityCode" column="city_code"/>
        <result property="province" column="province"/>
    </resultMap>

    <!--分页查询所有城市,使用了mybatis的分页查询,会自动将传递过来的页数和条数进行分页-->
    <select id="listCity" resultMap="cityMap">
        select city_id, city_name, city_code, province from city
        <where>
            <if test="province != null and province != ''">
                province = #{province}
            </if>
        </where>
    </select>
</mapper>

7.编写Main方法

public class Main {

    public static void main(String[] args) {
        // 通过Spring配置文件创建对象
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 获取service对象
        CityService service = context.getBean(CityService.class);
        // 调用分页查询方法
        PageInfo<City> pageInfo = service.listCity(1, 10, null);
        // 循环遍历
        pageInfo.getList().forEach(city -> System.out.println(city.getCityName()));
    }
}

8. 执行结果

在这里插入图片描述
整合mybatis完成