springBoot 快速入手

本文介绍了如何在SpringBoot项目中使用MyBatis进行数据库操作,包括配置数据库连接、定义实体类、创建Mapper接口和实现Service/Controller层调用。展示了如何执行查询所有公司的操作。
摘要由CSDN通过智能技术生成

server:
  port: 8888
spring:
  datasource:
    # 数据库连接配置
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mskk?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password:
# mybatis的相关配置
mybatis:
  # mapper 配置文件
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.geng.demo.mybatis.entity

package com.example.demo.entity;

public class Company {
    private int id;
    private String name;

    public Company(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

package com.example.demo.mapper;

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

import java.util.List;

@Mapper
public interface CompanyMapper {
    List<Company> findAll();
}

<?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.CompanyMapper">

    <resultMap id="CompanyMap" type="com.example.demo.entity.Company">
        <result column="id" property="id"/>
    </resultMap>

    <select id="findAll" resultMap="CompanyMap">
        SELECT * FROM company
    </select>
<!--    <select id="getUserById" resultMap="userResultMap">-->
<!--        SELECT * FROM user WHERE id = #{id}-->
<!--    </select>-->


</mapper>

package com.example.demo.service;

import com.example.demo.entity.Company;
import com.example.demo.mapper.CompanyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CompanyService {
    @Autowired
    private CompanyMapper companyMapper;
    public List<Company> findAll(){
        return companyMapper.findAll();
    }
}

package com.example.demo.controller;

import com.example.demo.entity.Company;
import com.example.demo.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    @RequestMapping("/abc")
    public List<Company> findAll(){
        return companyService.findAll();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值