Spring Boot 简单整合mysql

6 篇文章 0 订阅
3 篇文章 0 订阅

工具使用: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,即可访问

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值