Spring 与 MyBatis 框架集成
Spring 集成 MyBatis
为何要框架集成
Spring 通过 IoC 和 AoP 两大法宝,可以简化 MyBatis 框架配置和代码开发。
框架集成步骤
第①步:创建数据库表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
tb_user 表非常简单,只有一个主键 id
和一个字段name
第②步:IDEA 创建 Maven 项目
第③步:修改 pom.xml 配置添加 Maven 依赖包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springmybatisdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Spring版本 -->
<spring.version>5.2.3.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!-- 数据库驱动依赖(根据你使用的数据库选择) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<!-- lombok 依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<!-- 日志整合 slf4j门面设计模式与 log4j或log4j2一起使用-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.36</version>
</dependency>
<!-- 日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
第④步:创建 UserEntity 实体类
创建 entity 或 domain 包,并在包中创建 UserEntity 实体类,如下:
package com.binge.entity;
import lombok.*;
@Data
@AllArgsConstructor
public class UserEntity {
private Long id;
private String name;
}
第⑤步:创建 UserMapper 接口
创建 dao 包,并在包中创建 UserMapper 接口,如下:
package com.binge.dao;
import com.binge.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
public interface UserMapper {
void insert(UserEntity userEntity);
List<UserEntity> getList();
}
该接口提供了插入和查询数据库两个方法
第⑥步:创建 UserMapper 接口对应的 UserMapper.xml 映射文件
在 resources 下创建 mapper 文件夹,用于存放映射文件,然后创建 UserMapper.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="com.binge.dao.UserMapper">
<insert id="insert" parameterType="com.binge.entity.UserEntity" keyProperty="id" useGeneratedKeys="true">
<![CDATA[ INSERT INTO `tb_user` (name) VALUES (#{name})]]>
</insert>
<select id="getList" resultType="com.binge.entity.UserEntity">
<![CDATA[
SELECT id,name FROM tb_user
]]>
</select>
</mapper>
第⑦步:创建 IUserService 接口和 UserServiceImpl 实现类
创建 Service 包,并在包中创建 IUserService 接口,如下:
package com.binge.service;
import com.binge.entity.UserEntity;
import java.util.List;
public interface IUserService {
UserEntity insert(UserEntity userModel);
List<UserEntity> getList();
}
在 Service 包内创建 impl 包,用于存放 UserServiceImpl 实现类,如下:
package com.binge.service.impl;
import com.binge.entity.UserEntity;
import com.binge.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.binge.service.IUserService;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Transactional(rollbackFor = Exception.class)
@Override
public UserEntity insert(UserEntity userModel) {
userMapper.insert(userModel);
return userModel;
}
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
@Override
public List<UserEntity> getList() {
return userMapper.getList();
}
}
第⑧步:创建数据库配置文件 database.properties
在 resources 文件夹下创建 database.properties 文件,如下:
spring.datasource.url=jdbc:mysql://localhost:3306/binge?characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
注意:需要根据自己电脑的数据库信息修改以上配置
第⑨步:创建 Spring IoC 容器 spring-config.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:context="http://www.springframework.org/schema/context"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd">
<!-- 自动扫描注解 -->
<context:component-scan base-package="com.binge"/>
<!-- 引入数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${spring.datasource.driver-class-name}"/>
<property name="url" value="${spring.datasource.url}"/>
<property name="username" value="${spring.datasource.username}"/>
<property name="password" value="${spring.datasource.password}"/>
</bean>
<!-- MyBatis 扫描 mapper -->
<mybatis:scan base-package="com.binge.dao"/>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--设置entity实体类路径-->
<property name="typeAliasesPackage" value="com.binge.entity" />
<!--设置mapper映射文件路径-->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
</beans>
在 resources 文件夹下创建日志配置文件 log4j.properties,如下:
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
第⑩步:创建 SpringMyBatisTest 测试类
import com.binge.entity.UserEntity;
import com.binge.service.IUserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class SpringMybatisTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
IUserService userService = context.getBean(IUserService.class);
List<UserEntity> users = userService.getList();
System.out.println(users);
UserEntity userEntity = userService.insert(new UserEntity(null, "张三"));
System.out.println(userEntity);
}
}
运行测试类,结果如下:
[UserEntity(id=2, name=spring系列), UserEntity(id=3, name=spring系列), UserEntity(id=4, name=刘德华), UserEntity(id=5, name=郭富城), UserEntity(id=6, name=张学友), UserEntity(id=7, name=黎明), UserEntity(id=8, name=刘德华), UserEntity(id=9, name=郭富城), UserEntity(id=10, name=张学友), UserEntity(id=11, name=黎明), UserEntity(id=12, name=张三), UserEntity(id=13, name=张三), UserEntity(id=14, name=张三)]
UserEntity(id=15, name=张三)
Process finished with exit code 0
结果显示插入和查询数据,至此框架集成成功:)