Spring框架用配置文件整合Mybatis框架代码
时间: 2023-07-01 07:16:05 浏览: 112
Spring框架整合Mybatis框架
好的,下面是整合步骤:
1. 添加 Mybatis 和 Spring 的相关依赖包,可以在 Maven 中添加以下依赖:
```xml
<!-- Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- Spring 依赖 -->
<!-- Spring 核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- Spring 上下文依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- Spring JDBC 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
```
2. 在 Spring 配置文件中添加 Mybatis 和数据库连接相关配置,如下:
```xml
<!-- 数据库连接配置 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- Mybatis SqlSessionFactory 配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- Mybatis Mapper 扫描配置 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
```
3. 编写 Mybatis 的配置文件 mybatis-config.xml,配置 Mybatis 相关参数,如下:
```xml
<?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>
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<package name="com.example.entity"/>
</typeAliases>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
```
4. 编写 Mapper 接口和对应的 XML 文件,如下:
UserMapper.java
```java
public interface UserMapper {
User getUserById(Long id);
}
```
UserMapper.xml
```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.example.mapper.UserMapper">
<resultMap id="userMap" type="com.example.entity.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
</resultMap>
<select id="getUserById" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
```
5. 在代码中通过 Spring 的 IoC 容器获取 Mapper 对象并调用方法,如下:
```java
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
```
以上就是整合 Mybatis 和 Spring 的基本步骤。
阅读全文