Spring与MyBatis框架集成
引言
尽管Spring本身提供了Spring JDBC作为对JDBC的抽象和简化,但与MyBatis集成可以提供更多的功能和灵活性。MyBatis是一款优秀的持久层框架,它通过XML或注解的方式将SQL语句与Java方法进行绑定,提供了更直观和便捷的方式来管理数据库操作。集成Spring和MyBatis可以发挥两者的优势,Spring提供了事务管理、依赖注入等功能,而MyBatis负责处理数据库操作。这种集成可以简化开发过程,提高开发效率,并且允许更好地管理和优化SQL语句。
Spring不排斥各种优秀的框架,并提供对各种优秀框架的支持。
创建数据库表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`gender` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
在IDEA中新建Maven项目
选择New Project创建新的项目
选择Maven ---> 选择自己的SDK版本 ---> Next
填写项目的基本信息 ---> Finish
File ---> Settings ---> Build,Execution,Deployment ---> Build Tools ---> Maven
配置自己的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>com.cn.qrj</groupId>
<artifactId>SpringMyBatis</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>5.1.47</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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
创建User实体类
在main/java目录下创建com.cn.qrj.entity包,在包下面创建User实体类
package com.cn.qrj.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author: qrj
* @description 用户实体类
* @Date: 2023/9/12 17:12
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private Integer age;
private String gender;
}
创建UserMapper接口
在main/java目录下创建com.cn.qrj.mapper包,在包下面创建UserMapper接口,并定义如下一些方法。
package com.cn.qrj.mapper;
import com.cn.qrj.entity.User;
import java.util.List;
/**
* @author: qrj
* @description
* @Date: 2023/9/12 17:17
*/
public interface UserMapper {
//查询所有的用户
List<User> findAllUser();
//查询单个用户
User findUserById(Integer id);
//添加用户
int insertUser(User user);
//删除用户
int deleteUser(Integer id);
//修改用户
int update(User user);
}
创建UserMapper.xml映射文件
注意这里创建的UserMapper映射文件要和之前创建的UserMapper接口文件相对应。
在resources文件夹下创建mapper文件夹,并在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.cn.qrj.mapper.UserMapper">
<select id="findAllUser" resultType="com.cn.qrj.entity.User">
SELECT
*
FROM
USER;
</select>
<select id="findUserById" resultType="com.cn.qrj.entity.User">
SELECT
*
FROM
USER
WHERE
id = #{id}
</select>
<insert id="insertUser" parameterType="com.cn.qrj.entity.User">
INSERT INTO USER ( name, age, gender )
VALUE
( #{name}, #{age} , #{gender} )
</insert>
<delete id="deleteUser">
DELETE
FROM
USER
WHERE
id = #[id]
</delete>
<update id="updateUser" parameterType="com.cn.qrj.entity.User">
UPDATE USER
SET name = #{name},
age = #{age},
gender = #{gender}
WHERE
id = #{id}
</update>
</mapper>
创建IUserService接口和UserServiceImpl实现类
在main/java目录下创建com.cn.qrj.service包,在包中创建IUserService接口
package com.cn.qrj.service;
import com.cn.qrj.entity.User;
import java.util.List;
/**
* @author: qrj
* @description
* @Date: 2023/9/12 17:41
*/
public interface IUserService {
//查询所有的用户
List<User> findAllUser();
//查询单个用户
User findUserById(Integer id);
//添加用户
int insertUser(User user);
//删除用户
int deleteUser(Integer id);
//修改用户
int updateUser(User user);
}
在com.cn.qrj.service包下创建Impl包,并创建UserServiceImpl实现类
package com.cn.qrj.service.Impl;
import com.cn.qrj.entity.User;
import com.cn.qrj.mapper.UserMapper;
import com.cn.qrj.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author: qrj
* @description
* @Date: 2023/9/12 17:45
*/
@Service //控制反转
public class UserServiceImpl implements IUserService {
@Autowired //依赖注入
private UserMapper userMapper;
@Override
public List<User> findAllUser() {
return userMapper.findAllUser();
}
@Override
public User findUserById(Integer id) {
return userMapper.findUserById(id);
}
@Override
public int insertUser(User user) {
int result = userMapper.insertUser(user);
return result;
}
@Override
public int deleteUser(Integer id) {
int result = userMapper.deleteUser(id);
return result;
}
@Override
public int updateUser(User user) {
int result = userMapper.updateUser(user);
return result;
}
}
创建数据库配置文件db.properties
在resources文件夹下创建db.properties文件
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/spring_mybatis?useSSL=false
db.username=root
db.password=123456
注意:以上信息要根据自己的数据库配置
创建日志配置文件log4j.properties
在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
创建Spring IOC 容器spring-config.xml文件
在resources文件夹下创建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.cn.qrj"/>
<!-- 引入数据库配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!-- MyBatis 扫描 mapper -->
<mybatis:scan base-package="com.cn.qrj.mapper"/>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--设置entity实体类路径-->
<property name="typeAliasesPackage" value="com.cn.qrj.entity" />
<!--设置mapper映射文件路径-->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
</beans>
创建测试类SpringMyBatisTest测试类
import com.cn.qrj.entity.User;
import com.cn.qrj.service.IUserService;
import com.cn.qrj.service.Impl.UserServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* @author: qrj
* @description
* @Date: 2023/9/12 18:03
*/
public class SpringMyBatisTest {
public static void main(String[] args) {
//加载IOC容器
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-config.xml");
System.out.println(ioc);
IUserService userService = ioc.getBean(UserServiceImpl.class);
List<User> userList = userService.findAllUser();
for (User user : userList){
System.out.println(user);
}
User user = new User(null,"黎明",25,"男");
if (userService.insertUser(user) > 0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
}
}
运行测试类,得到如下结果:
查询结果和插入结果都已成功实现,框架集成成功!
热门相关:豪门蜜爱:独宠天后小萌妻 上将大叔,狼来了! 楚氏赘婿 重生之女将星 嫡嫁千金