准备工作
- JDK 8+
- Maven
引入依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.6.RELEASE</version> </dependency> <!-- mybatis-plus插件依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.1.1</version> </dependency>
编写jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mp?useSSL=false&serverTimezone=GMT%2B8 jdbc.username=root jdbc.password=123456
在applicationContext.xml中引入jdbc.properties
<!--引⼊properties--> <context:property-placeholder location="classpath:jdbc.properties"/>
配置dataSource
<!--dataSource--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>
配置 MapperScan
<!--扫描mapper接⼝,使用的依然是mybatis原生的扫描器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mgyboom.mapper"/> </bean>
调整 SqlSessionFactory 为 MyBatis-Plus 的 SqlSessionFactory
<!--这⾥使用MP提供的sqlSessionFactory,完成spring与mp的整合--> <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="com.mgyboom.pojo"/> <!-- 当mybatis的xml文件和mapper接口不在相同包下时,需要用mapperLocations属性指定xml文件的路径。 *是个通配符,代表所有的文件,**代表所有目录下 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <!-- <property name="configLocation" value="classpath:sqlMapConfig.xml"/> --> </bean>
代码示例
https://gitee.com/mgyboom/spring-mp