spring配置mybatis
时间: 2023-12-31 10:24:55 浏览: 79
Spring集成MyBatis框架
在Spring中配置MyBatis可以通过以下步骤实现:
1. 添加MyBatis和Spring Boot MyBatis Starter的依赖项到项目的pom.xml文件中:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
```
2. 创建一个MyBatis的配置类,用于配置MyBatis的相关属性和设置:
```java
@Configuration
@MapperScan("com.example.mapper") // 指定Mapper接口所在的包
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory.getObject();
}
}
```
3. 创建Mapper接口和对应的Mapper XML文件,用于定义数据库操作的SQL语句和映射关系。例如,创建一个UserMapper接口和对应的UserMapper.xml文件:
```java
@Mapper
public interface UserMapper {
User getUserById(int id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
```
```xml
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" resultType="com.example.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.model.User">
INSERT INTO users (id, name, age) VALUES (#{id}, #{name}, #{age})
</insert>
<update id="updateUser" parameterType="com.example.model.User">
UPDATE users SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM users WHERE id = #{id}
</delete>
</mapper>
```
4. 在Spring Boot的配置文件application.properties或application.yml中配置数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
5. 在需要使用Mapper的地方,通过@Autowired注解注入Mapper,并调用相应的方法进行数据库操作:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.getUserById(id);
}
public void insertUser(User user) {
userMapper.insertUser(user);
}
public void updateUser(User user) {
userMapper.updateUser(user);
}
public void deleteUser(int id) {
userMapper.deleteUser(id);
}
}
```
阅读全文