温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MyBatis在Spring Boot中的SQL模板

发布时间:2024-09-11 16:54:53 来源:亿速云 阅读:79 作者:小樊 栏目:编程语言

MyBatis 是一个优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。在 Spring Boot 中,我们可以使用 MyBatis 作为数据访问层的实现。

要在 Spring Boot 中使用 MyBatis,你需要按照以下步骤进行操作:

  1. 添加依赖

在你的 pom.xml 文件中添加 MyBatis 和 MyBatis-Spring-Boot-Starter 的依赖:

   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.1.4</version>
</dependency>
  1. 配置 MyBatis

application.propertiesapplication.yml 文件中添加 MyBatis 的配置信息:

# application.properties
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity

或者

# application.yml
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.entity
  1. 创建实体类

创建一个实体类,例如 User.java

package com.example.demo.entity;

public class User {
    private Long id;
    private String name;
    private Integer age;

    // getter and setter methods
}
  1. 创建 Mapper 接口

创建一个名为 UserMapper.java 的接口,并定义相应的方法:

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user")
    List<User> findAll();
}
  1. 创建 Mapper XML 文件

resources/mapper 目录下创建一个名为 UserMapper.xml 的文件,用于编写 SQL 语句:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.demo.mapper.UserMapper">
   <resultMap id="BaseResultMap" type="com.example.demo.entity.User">
        <id column="id" property="id" jdbcType="BIGINT"/>
       <result column="name" property="name" jdbcType="VARCHAR"/>
       <result column="age" property="age" jdbcType="INTEGER"/>
    </resultMap>

   <select id="findAll" resultMap="BaseResultMap">
        SELECT * FROM user
    </select>
</mapper>
  1. 使用 Mapper

在你的服务类或控制器类中,通过 @Autowired 注入 UserMapper,然后调用相应的方法来执行 SQL 语句:

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/users")
    public List<User> getUsers() {
        return userMapper.findAll();
    }
}

这样,你就可以在 Spring Boot 项目中使用 MyBatis 来编写和执行 SQL 语句了。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI