springboot快速整合mybatis连接mysql

1、新建一个springboot项目

2、选择需要的依赖,然后等待依赖的下载完成

 

3、快速配置application.properties文件

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql://localhost:3306/hello

mybatis.mapper-locations=classpath:mapper/*.xml   //实现mapper接口配置

4、新建6个文件夹以及在文件夹下创建文件        

 

5、编写entity-Person

package com.example.entity;

import lombok.Data;

@Data
public class Person {
    private String name;       //这里的属性和数据库表的字段一致
    private String age;
}

6、编写mapper文件

PersonMapper.java

package com.example.mapper;

import com.example.entity.Person;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface PersonMapper {
    Person getPerson();
}

personMapper.xml 

<?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.mapper.PersonMapper">
    <select id="getPerson" resultType="com.example.entity.Person">
        select * from person
    </select>
</mapper>

7、编写Service

PersonService.java

package com.example.service;

import com.example.entity.Person;

public interface PersonService {
    Person getPerson();
}

 PersonServiceImpl.java

package com.example.service.Impl;

import com.example.entity.Person;
import com.example.mapper.PersonMapper;
import com.example.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonMapper personMapper;

    @Override
    public Person getPerson() {
        Person person = personMapper.getPerson();
        return person;
    }
}

8、编写controller

Controller.java

package com.example.controller;

import com.example.entity.Person;
import com.example.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonController {

    @Autowired
    private PersonService personService;

    @GetMapping("")
    public Person getPerson(){
        Person person = personService.getPerson();
        return person;
    }

}

9、启动项目访问地址即可

10、注意事项 

  1. 各个类的注解需要检查是否齐全
  2. 数据库url可以先使用idea右侧的Database测试一下是否连接成功
  3. 数据库的名称配置项是username而不是name,曾经因为这个找不不少时间!!!
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值