首页主机资讯springboot如何整合mybatis

springboot如何整合mybatis

时间2024-01-17 18:37:02发布访客分类主机资讯浏览645
导读:要将Spring Boot与MyBatis整合,可以按照以下步骤操作: 步骤1:在pom.xml文件中添加MyBatis和MyBatis-Spring-Boot-Starter依赖。 <dependency> <g...

要将Spring Boot与MyBatis整合,可以按照以下步骤操作:

步骤1:在pom.xml文件中添加MyBatis和MyBatis-Spring-Boot-Starter依赖。

dependency>
    
    groupId>
    org.mybatis.spring.boot/groupId>
    
    artifactId>
    mybatis-spring-boot-starter/artifactId>
    
    version>
    2.1.4/version>
    
/dependency>
    

步骤2:配置数据库连接信息和MyBatis属性。

在application.properties或application.yml文件中添加以下配置:

spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=db_username
spring.datasource.password=db_password

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

步骤3:创建MyBatis的Mapper接口和对应的XML文件。

创建一个Mapper接口,例如UserMapper.java,并编写Mapper方法。

import org.apache.ibatis.annotations.Mapper;
    
import org.apache.ibatis.annotations.Select;
    

import java.util.List;


@Mapper
public interface UserMapper {
    

    @Select("select * from users")
    ListUser>
     getAllUsers();

}
    

在resources/mapper目录下创建UserMapper.xml文件,配置SQL语句。

mapper namespace="com.example.mapper.UserMapper">
    

    resultMap id="BaseResultMap" type="com.example.entity.User">
    
        id column="id" property="id" />
    
        result column="name" property="name" />
    
        result column="email" property="email" />
    
    /resultMap>
    

    select id="getAllUsers" resultMap="BaseResultMap">
    
        select * from users
    /select>
    
/mapper>

步骤4:创建Service和Controller。

创建一个UserService接口和UserServiceImpl实现类。

public interface UserService {
    

    ListUser>
     getAllUsers();

}


@Service
public class UserServiceImpl implements UserService {
    

    @Autowired
    private UserMapper userMapper;
    

    public ListUser>
 getAllUsers() {
    
        return userMapper.getAllUsers();

    }

}


@RestController
public class UserController {
    

    @Autowired
    private UserService userService;
    

    @GetMapping("/users")
    public ListUser>
 getAllUsers() {
    
        return userService.getAllUsers();

    }

}
    

以上就是整合Spring Boot和MyBatis的基本步骤。在Spring Boot启动时,MyBatis会自动根据配置文件和注解扫描Mapper接口,并生成代理实现类。可以使用这些Mapper接口来访问数据库。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: springboot如何整合mybatis
本文地址: https://pptw.com/jishu/582773.html
java多实现如何找到具体的实现类 java如何定义抽象类

游客 回复需填写必要信息