Spring Boot连接MySQL数据库

1. pom.xml添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>    

2. application.properties添加数据库配置

spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true

如果数据库连接写成spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot ,由于MySQL版本的问题,可能会有以下的错误,在后面加上“?serverTimezone=GMT%2B8”,设置下时区,解决。

设置驱动,spring.datasource.driver-class-name=com.mysql.jdbc.Driver会有下面红色的警告信息。说的是`com.mysql.jdbc.Driver‘被弃用了,要使用新的驱动`com.mysql.cj.jdbc.Driver‘,改成`com.mysql.cj.jdbc.Driver‘以后一切正常。

Loading class `com.mysql.jdbc.Driver‘. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver‘. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

3. 添加实体类

@Entity代表这是一个实体类,@Table(name=”user”)用来对应数据库中的use表,@Id用来表达主键,@Column(name=”id”)表明一个id属性。

@GeneratedValue使主键自增,如果还有疑问,可参考@GeneratedValue源码解析

package com.example.demo.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;
    @Column(name = "username")
    private String userName;
    @Column(name = "password")
    private String passWord;

    public User() {
        super();
    }

    public User(String userName, String passWord) {
        super();
        this.userName = userName;
        this.passWord = passWord;
    }

    public Long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

}

4. 添加Dao

Dao层主要用来实现对数据库的增、删、查、改。 dao只要继承JpaRepository类就可以,几乎可以不用写方法,可以根据方法名来自动的生产SQL,比如findByUserName 会自动生产一个以 userName 为参数的查询方法。

package com.example.demo.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.demo.domain.User;

public interface UserRepository extends JpaRepository<User, Long> {

    User findByUserName(String userName);

}

5. 添加Controller

package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.UserRepository;
import com.example.demo.domain.User;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/getAllUser")
    @ResponseBody
    public List<User> findAll() {
        List<User> list = new ArrayList<User>();
        list = userRepository.findAll();
        return list;
    }

    @RequestMapping("/getByUserName")
    @ResponseBody
    public User getByUserName(String userName) {
        User user = userRepository.findByUserName(userName);
        return user;
    }

}

工程添加文件后工程结构图:

6. 新建数据库

新建数据库mysql://localhost:3306/spring_boot ,必须的一个步骤。hibernate虽然会自动新建表,但是数据库还是要手动建好的。

使用Navicat新建本地数据库,连接名上面右键- >新建数据库 ->填写数据库信息 - > 确定。

在user表中,插入两条测试数据:

7. 测试

启动项目。用Postman发送请求进行测试:

http://localhost:8080//user/getAllUser :

http://localhost:8080//user/getByUserName?userName=Turing :

原文地址:https://www.cnblogs.com/xing-nb/p/12146197.html

时间: 2024-08-29 21:33:57

Spring Boot连接MySQL数据库的相关文章

Spring Boot 连接MySql数据库

Spring Boot 以后也许会成为入门Spring的首选! 记一下Spring Boot 成功连接Mysql数据库的方法步骤! 一.新建Maven工程,不全Maven所需文件夹,在pom.xml引入SpringBoot的依赖包!可以参照:http://www.cnblogs.com/liangblog/p/5207855.html 二.有两种方法与数据库建立连接,一种是集成Mybatis,另一种用JdbcTemplate (1).用JdbcTemplate <dependency> <

Spring Boot连接Mysql数据库问题解决

在spring Boot项目中使用mysql数据库进行数据库的增删查改,出现以下错误: Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2017-06-15 15:04:37.122 ERROR 10072 --- [ restartedMain] o.s.boot.SpringApplication

spring boot 连接mysql 错误The server time zone value &#39;&#214;&#208;&#185;&#250;&#177;&#234;&#215;&#188;&#202;&#177;&#188;&#228;&#39; is unrecognized or represents more than one

1.spring boot 整合mybatis 连接mysql时错误 The server time zone value '?D1ú±ê×?ê±??' is unrecognized or represents more than one 2.解决: jdbc:mysql://localhost:3306/new_schema?useSSL=false&serverTimezone=GMT%2B8 在地址后面加上 &serverTimezone=GMT%2B8%2B是+号的意思,这个意思

Spring Boot连接MySQL长时间不连接后报错`com.mysql.cj.core.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.`的解决办法

报错:com.mysql.cj.core.exceptions.ConnectionIsClosedException: No operations allowed after connection closed. 添加 &autoReconnect=true 无济于事,此选项好像仅对 MySQL 5之前的版本有效. 原因 Mysql服务器默认的"wait_timeout"是8小时,也就是说一个connection空闲超过8个小时,Mysql将自动断开该connection.这

Spring Boot连接MySQL报错“Internal Server Error”的解决办法

报错信息如下: {timestamp: "2018-06-14T03:48:23.436+0000", status: 500, error: "Internal Server Error",-} error : "Internal Server Error" message : "Could not open JDBC Connection for transaction; nested exception is java.sql.S

记录一次Spring boot 搭建框架连接Mysql数据库注解事务不回滚的故障

搭建了一个新框架,使用了spring boot 替换以简化原来繁杂的spring配置,使用Spring注解管理事务,持久层使用mybatis. 连接mysql数据库完成项目的过程中发现不支持事务,因为用的新框架自己本身也不是很了解,刚开始一直以为是自己的框架搭建的有问题, 后来发现是mysql数据库引擎的问题 解决方案 MyISAM不支持事物,InnoDB支持事物 先检查你的mysql版本 ,mysql 4.0系列之前是不支持事务的.    SELECT VERSION(); 检查你的数据库支持

Spring Boot 2.0(五):Docker Compose + Spring Boot + Nginx + Mysql 实践

我知道大家这段时间看了我写关于 docker 相关的几篇文章,不疼不痒的,仍然没有感受 docker 的便利,是的,我也是这样认为的,I know your felling . 前期了解概念什么的确实比较无聊,请不要着急精彩马上开始,当大家对 docker 相关概念有所了解之后,后面我会结合 Spring Boot 给大家来一系列的小例子,会让大家感受到使用 Docker 就是这么爽! 今天给大家演出的导演是 Docker 家族的 docker-compare ,主演是 Spring Boot.

Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件

上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybatis和pagehelper 关于mybatis和pagehelper的介绍,可以自行博客,网上很多类似的博客,这里,我直接上代码和项目搭建教程. 1.配置文件:在配置文件application.yml中配置MySql数据库连接池和Mybatis扫描包以及PageHelper分页插件 1 mybati

如何用IDEA创建springboot(maven)并且整合mybatis连接mysql数据库和遇到的问题

1.New->Project 2.点击next 3.在Group栏输入组织名,Artifact就是项目名.其它选择默认就好,直接Next 4.添加依赖 5.修改您希望放项目的位置,点击finish,等待idea下载springboot项目模板和相关的依赖 项目构建完成后的目录结构 6.如果需要用mybatis连接mysql数据库 a.添加连接数据库的依赖(在pom.xml中添加以下内容,maven将自动把相关依赖放到maven仓库中,然后放到项目中) <!--连接数据库--><de