SpringBoot 结合MyBatis读取MySQL 数据

本文详细描述了如何在SpringBoot项目中使用MyBatis进行MySQL数据库操作,包括项目结构建立、数据表管理、代码实现(包括Controller、Service、Mapper和Domain)以及编译运行的过程。
摘要由CSDN通过智能技术生成

MyBatis的作用

读取MySQL 数据库数据,将数据转为Java 类对象,供SpringBoot 程序使用

实例

一、新建项目

项目名可自己命名

二、新建项目的子模块

新建模块mybatis

三、 MySQL 数据库配置、添加数据

创建数据库

添加表

添加表字段

设置好后点击保存,填写表名

添加数据

四、编写代码

新建controller、service、mapper、domain 包
新建mapper 资源目录 

新建controller、service、mapper、domain 对应的Java 文件
新建mapper 资源目录Java mapper 对应的XML 文件

添加注解

HelloController

package com.example.mybatis.controller;

import com.example.mybatis.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatis.service.UserService;
import java.util.HashMap;
import java.util.List;

@RestController
public class HelloController {
    @Autowired
    private UserService userService;

    @GetMapping("/hello")
    public List<User> hello()
    {
        return userService.selectAllUser();
    }
}
 

User

package com.example.mybatis.domain;

public class User {
    public int id;
    private String name;
    private int age;
    public int sex;
    public String createTime;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
}

UserMapper

package com.example.mybatis.mapper;

import com.example.mybatis.domain.User;

import java.util.List;

public interface UserMapper {
    List<User> selectAllUser();

}

UserService

package com.example.mybatis.service;

import com.example.mybatis.domain.User;
import com.example.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> selectAllUser()
    {
        return userMapper.selectAllUser();
    }
}

编译代码、构建程序
执行SpringBoot 程序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值