spring4329 集成mybatis
- 添加依赖
在 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.29.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
- 配置数据源
在 Spring 配置文件中配置数据源,例如:
<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="123456" />
</bean>
- 配置 MyBatis 的 SqlSessionFactory
在 Spring 配置文件中配置 MyBatis 的 SqlSessionFactory,例如:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
其中,mapperLocations 指定 MyBatis Mapper 文件的位置。
- 配置 MyBatis 的 MapperScannerConfigurer
在 Spring 配置文件中配置 MyBatis 的 MapperScannerConfigurer,例如:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
其中,basePackage 指定 Mapper 接口的包路径,sqlSessionFactoryBeanName 指定 SqlSessionFactory 的名称。
- 配置事务管理器
在 Spring 配置文件中配置事务管理器,例如:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
- 使用 MyBatis
在 Mapper 接口中定义 SQL 语句,并使用 MyBatis 提供的注解或 XML 文件来映射 SQL 语句和 Java 对象。例如:
public interface UserMapper {
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
}
或者使用 XML 文件:
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" resultType="com.example.entity.User">
select * from user where id = #{id}
</select>
</mapper>
然后在 Service 层中注入 Mapper 接口,并调用相应的方法即可。
参考链接:
- https://mybatis.org/spring/zh/getting-started.html
- https://www.jianshu.com/p/030e1e4e7a1
原文地址: https://www.cveoy.top/t/topic/fqWb 著作权归作者所有。请勿转载和采集!