mybatis springboot整合

来源:undefined 2025-06-04 09:28:47 0

MyBatis是一个支持普通 SQL 查询、存储过程和高级映射的持久化框架。它和Spring Boot结合起来可以让我们更方便地进行数据库操作。在这篇文章中,我将介绍如何在Spring Boot项目中整合MyBatis。

首先,我们需要在pom.xml文件中添加MyBatis和Mybatis-Spring的依赖:

```xml

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.2.0

```

接下来,我们需要配置MyBatis的数据源和SqlSessionFactory。在application.properties文件中添加数据库连接信息:

```properties

spring.datasource.url = jdbc:mysql://localhost:3306/mybatisdb

spring.datasource.username = root

spring.datasource.password = password

spring.datasource.driver-class-name = com.mysql.jdbc.Driver

```

然后,在application.properties文件中添加MyBatis的配置信息:

```properties

mybatis.type-aliases-package = com.example.model

mybatis.mapper-locations = classpath:mapper/*.xml

```

创建一个数据模型类User.java:

```java

package com.example.model;

public class User {

private Long id;

private String name;

private int age;

// getter and setter methods

}

```

接着在resources目录下创建一个mapper目录,并添加一个UserMapper.xml文件,定义User的操作:

```xml

"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

select * from user where id = #{id}

insert into user(name

age) values(#{name}

#{age})

```

创建一个UserMapper接口:

```java

package com.example.mapper;

import com.example.model.User;

public interface UserMapper {

User getUserById(Long id);

void insertUser(User user);

}

```

*,在启动类中添加@MapperScan注解,扫描Mapper接口所在的包:

```java

package com.example;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

@MapperScan("com.example.mapper")

public class MybatisDemoApplication {

public static void main(String[] args) {

SpringApplication.run(MybatisDemoApplication.class

args);

}

}

```

这样就完成了MyBatis和Spring Boot的整合。现在我们可以在服务类中注入UserMapper接口,然后调用其中定义的方法来进行数据库操作。例如:

```java

package com.example.service;

import com.example.mapper.UserMapper;

import com.example.model.User;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service

public class UserService {

@Autowired

private UserMapper userMapper;

public User getUserById(Long id) {

return userMapper.getUserById(id);

}

public void insertUser(User user) {

userMapper.insertUser(user);

}

}

```

这样就可以在服务类中直接调用MyBatis的方法来操作数据库了。整合MyBatis和Spring Boot可以让我们更方便地进行数据库操作,提高开发效率。希望这篇文章对你有所帮助!

上一篇:ddl操作 下一篇:connectionsmongoose官方教程

最新文章