Spring Boot 简单整合mysql

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Little_Matches/article/details/79863827

工具使用:InteIIij IDEA(eclipse整合较麻烦) JDK1.8 mysql5.7

1.首先File->new Project->Spring Initialzr
这里写图片描述
2.填写默认信息
这里写图片描述
3.选择要添加的依赖,漏了也没关系,之后可以在pom.xml文件里面补
这里写图片描述

4.点击完成后就可以生成基本目录了.
5.按照下图创建文件
这里写图片描述

6.首先看下BaseApplication,这个必须放在自定义的包外面,不然会报错的.
这里写图片描述

7.定义数据实体,我这里定义比较多:
这里写图片描述
8.AccountDao:

package top.littlematch.base.login.dao;

import org.springframework.data.repository.CrudRepository;
import top.littlematch.base.login.model.Account;

public interface AccountDao extends CrudRepository<Account,Integer> {
}

9.AccountService

package top.littlematch.base.login.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.littlematch.base.login.dao.AccountDao;
import top.littlematch.base.login.model.Account;

import java.util.Optional;

@Service
public class AccountService {
    @Autowired
    private AccountDao accountDao;
    @Transactional
    public Account findById(Integer id){
    //findById方法继承自CrudRepository
        Optional<Account> account=accountDao.findById(id);
        return account.orElse(null);
    }
}

10.LoginController

package top.littlematch.base.login.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.littlematch.base.login.model.Account;
import top.littlematch.base.login.service.AccountService;

@RestController
@RequestMapping("/index")
public class LoginController {
    @Autowired
    private AccountService accountService;

    @GetMapping("/index")
    public Object index(){
        Account account=accountService.findById(1);

        return account;
    }
}

11.application.properties 基本配置

server.port=8080

server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8


spring.datasource.url=jdbc:mysql://localhost:3306/db_base?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

启动BaseApplication, 访问localhost://8080/index/index,即可访问

猜你喜欢

转载自blog.csdn.net/Little_Matches/article/details/79863827