SpringBoot学习之路---整合基于注解的Mybatis

SpringBoot学习了那么久了,总要拿出来试试操作数据库了吧。以往我们使用JDBC或是JdbcTemplate来操作数据库时,往往开发效率太低,所以我们平时会用到Mybatis框架来作为持久层的技术。这一篇博客来记录一下SpringBoot如何整合基于注解的MyBatis


要使用到Mybatis框架技术首先需要引入相关的jar包,之前我们就介绍过了SpringBoot是通过一个有一个的starter来管理一个又一个的jar包及相关依赖,这里我们也是一样,不过我们使用SpringBoot initializr来创建项目时,选择好相应的模块,它会自动帮我们导入starter
在这里插入图片描述
选择这四个模块(选择web模块是为了显示方便)

由于这篇博客是记录基于注解的,所以就可以直接来编写mapper了,不需要配置文件.在此之前我们需要先建好表和对应的JavaBean对象

表:
在这里插入图片描述
JavaBean:

public class user implements Serializable {
    private Integer uid;
    private String username;
    private String password;

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "user{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

之后还要选定数据源,我们这里选用默认的就好,直接在全局配置文件中配置即可:

spring:
  datasource:
    username: root
    password: ***
    url: jdbc:mysql://localhost:3306/demo
    driver-class-name: com.mysql.jdbc.Driver

在前期工作后,我们就可以直接编写mapper层的代码了,这里编写增删改查的对应方法:

@Mapper
public interface UserMapper {

    @Select("select * from user where uid = #{uid}")
    public User findUserByUid(Integer uid);

    @Delete("delete from user where uid = #{uid}")
    public void deleteUserByUid(Integer uid);

    @Insert("insert into user(username,password) values(#{username},#{password})")
    public Integer insertUser(User user);

    @Update("update user set username = #{username} password = #{password} where uid = #{uid}")
    public Integer updateUser(User user);
}

这里insertupdate方法有返回值,是为了后面介绍一个注解方便观察是否操作成功.

接下来编写controller层(因为没有啥工程量,跳过service层),为了方便编写代码,这里直接全部方法都使用Get请求来接受。

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/find/{uid}")
    public User find(@PathVariable Integer uid){

        return userMapper.findUserByUid(uid);
    }

    @GetMapping("/add")
    public User addUser(User user){
        userMapper.insertUser(user);

        return user;
    }

    @GetMapping("/delete/{uid}")
    public String deleteUser(@PathVariable Integer uid){
        userMapper.deleteUserByUid(uid);

        return "已经删除";
    }

    @GetMapping("/update")
    public User updateUser(User user){
        userMapper.updateUser(user);

        return user;
    }
}

接着在浏览器访问,先访问addUser方法
在这里插入图片描述
我们看到插入执行,在调用查询方法看看是否成功:
在这里插入图片描述
到这里就成功了,其他两个方法原理也是一样,这里就不一一调用了。但是还有一个问题,addUser的json返回值没有uid,这样就看不到插入数据的uid,我们只需要在mapper的对应方法上加上这条注解

@Options(useGeneratedKeys = true,keyProperty = "uid")

这条注解是Mybatis的原生注解,前面的属性表示获取数据库自增生成的主键,后面的表示要注入的JavaBean对象的属性名

接着在测试一下
在这里插入图片描述
可以看到在数据库中的uid了。


这是基于注解的Mybatis整合,操作起来比较简单,如果觉得不错的话,点个赞。咱们共勉加油哈.

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!要在Spring Boot整合MyBatis-Plus,你可以按照以下步骤进行操作: 步骤1:添加依赖 在你的Spring Boot项目的pom.xml文件中,添加MyBatis-Plus的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> ``` 请确保将`最新版本号`替换为MyBatis-Plus最新的版本号。 步骤2:配置数据源 在application.properties(或application.yml)文件中,配置数据库连接信息,例如: ```yaml spring.datasource.url=jdbc:mysql://localhost:3306/db_example spring.datasource.username=db_username spring.datasource.password=db_password spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 请将`db_example`、`db_username`和`db_password`分别替换为你的数据库名称、用户名和密码。 步骤3:创建实体类和Mapper接口 创建对应的实体类,并使用`@TableName`注解指定数据库表名。然后创建Mapper接口,继承自`BaseMapper`。 ```java import com.baomidou.mybatisplus.annotation.TableName; @TableName("user") public class User { private Long id; private String username; private String email; // getters and setters } ``` ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface UserMapper extends BaseMapper<User> { } ``` 步骤4:编写Service和Controller层代码 在Service层中,可以通过注入Mapper对象来使用MyBatis-Plus提供的便捷方法。例如: ```java import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.selectById(id); } // 其他业务逻辑方法 } ``` 在Controller层中,可以直接调用Service层的方法来处理请求。例如: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class UserController { @Resource private UserService userService; @GetMapping("/users/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } // 其他请求处理方法 } ``` 这样,你就完成了Spring BootMyBatis-Plus的整合。你可以根据自己的需求,使用MyBatis-Plus提供的便捷方法来进行数据库操作。 希望对你有所帮助!如果还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值