spring集成mabatis的配置文件
时间: 2023-11-11 09:31:38 浏览: 32
好的,以下是Spring集成MyBatis的配置文件示例:
1. 首先,在pom.xml文件中添加以下依赖:
```xml
<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>
```
2. 在Spring的配置文件中添加以下内容:
```xml
<!-- 数据源配置 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- MyBatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.example.model"/>
<property name="mapperLocations" value="classpath*:mapper/*.xml"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.dao"/>
</bean>
```
其中,dataSource为数据源配置,sqlSessionFactory是MyBatis的会话工厂配置,MapperScannerConfigurer用于扫描Mapper接口。
3. 在resources目录下添加mybatis-config.xml文件,用于配置MyBatis的全局参数,例如:
```xml
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
</configuration>
```
4. 在resources目录下添加Mapper映射文件,例如UserMapper.xml,用于配置SQL语句,例如:
```xml
<mapper namespace="com.example.dao.UserDao">
<select id="getUserById" parameterType="int" resultType="com.example.model.User">
select * from user where id = #{id}
</select>
</mapper>
```
5. 在Java代码中使用Mapper接口,例如:
```java
@Autowired
private UserDao userDao;
User user = userDao.getUserById(1);
```
以上就是Spring集成MyBatis的配置文件示例,希望对你有帮助。