spring boot框架搭建-6 链接mysql以及配置jpa

本文详细介绍了如何在SpringBoot项目中配置并使用MySQL数据库和JPA进行数据操作,包括依赖引入、属性配置、实体类创建、仓库层定义、业务层实现以及控制器调用的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做了前期的配置之后,我们现在需要链接数据库,这里将以mysql和jpa演示。
第一步,在pom.xml中引入mysql以及jpa的依赖

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
</dependency>	

第二步,在application.properties中,配置jpa及mysql的链接方式

#通用数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#test为数据库名称 
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=123456

# JPA 相关配置
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
#这个地方也最好加上,这样才能自动更新表
spring.jpa.hibernate.ddl-auto=update

第三步,建立实体类,user

package com.example.wx.entity;

import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

/**
 * Created by w on 2019/2/28.
 */
@Data
@NoArgsConstructor
@Entity//这个表示不能少
@Table(name="user")//表名
public class User {
    @Id//主键 不能缺
    @GeneratedValue(strategy= GenerationType.IDENTITY)//设置自增长
    private Long id;
    //用户姓名
    @Column(length = 50)//字段长度
    private String name;
    //邮箱
    @Column(length = 50)
    private String email;
    //性别
    @Column(length = 2)
    private String sex;
    //手机
    @Column(length = 20)
    private String mobile;
    //QQ
    @Column(length = 20)
    private String QQ;
}

第四步,建立仓库层,引入注解,继承JpaRepository

package com.example.wx.repository;

import com.example.wx.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by w on 2019/2/28.
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

第六步,建立业务层,IUserSerivce,及UserServiceImpl,在里面写业务代码

package com.example.wx.service;

import com.example.wx.entity.User;

/**
 * Created by w on 2019/2/28.
 */
public interface IUserService {
    //新增一个User
    void saveUser(User user);
}

实现类

package com.example.wx.service.impl;

import com.example.wx.entity.User;
import com.example.wx.repository.UserRepository;
import com.example.wx.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Created by w on 2019/2/28.
 */
@Service
public class UserServiceImpl implements IUserService{
    @Autowired
    UserRepository userRepository;

    @Override
    @Transactional
    public void saveUser(User user) {
        userRepository.save(user);
    }
}

第7步,调用就完事了

package com.example.wx.controller;

import com.example.wx.common.core.exception.MyException;
import com.example.wx.common.core.ret.ApiResult;
import com.example.wx.entity.User;
import com.example.wx.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by w on 2019/2/28.
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;

    @RequestMapping("/demo")
    ApiResult demo(@RequestParam String name)
    {
        ApiResult apiResult = new ApiResult();
        apiResult.setData(name);
        return apiResult;
    }

    //异常测试
    @RequestMapping("/test")
    ApiResult test()
    {
        throw new MyException("自定义异常测试");
    }

    //新增一个User
    @RequestMapping("/saveUser")
    public ApiResult saveUser(@RequestBody User user)
    {
        userService.saveUser(user);
        return new ApiResult();
    }
}

接口调用

上一篇,spring boot框架搭建-5 自定义异常以及全局异常捕捉
下一篇,spring boot框架搭建-7 建立数据传输对象dto以及映射ModelMapper

### Spring Boot 使用 spring-boot-starter-data-jpa 连接 MySQL 5.7 的配置教程 #### 添加 Maven 依赖 为了实现与 MySQL 数据库的交互,需要在项目的 `pom.xml` 文件中添加以下两个依赖项: ```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> ``` 上述依赖分别用于支持 JPA 功能和提供 MySQL 数据库驱动程序[^1]。 --- #### 配置 application.properties 或 application.yml 在 Spring Boot 中,可以通过修改 `application.properties` 文件来设置数据库连接参数。以下是针对 MySQL 5.7 的典型配置示例: ```properties # 数据源配置 spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=your_password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Hibernate 和 JPA 设置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect ``` 解释如下: - **spring.datasource.url**: 定义了 JDBC URL 地址,需替换为实际使用的数据库名称、主机地址和端口。 - **spring.datasource.username/password**: 替换为自己的 MySQL 用户名和密码。 - **spring.jpa.hibernate.ddl-auto**: 控制数据库 schema 自动生成行为(如 update/create/drop 等)。 - **spring.jpa.properties.hibernate.dialect**: 指定 Hibernate 对应的方言类,适用于 MySQL 5.x 版本[^2]。 如果更倾向于 YAML 格式的配置,则可改为: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC username: root password: your_password driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate: dialect: org.hibernate.dialect.MySQL5InnoDBDialect ``` --- #### 创建实体类 (Entity) 定义一个简单的实体类作为数据模型。例如创建名为 `User` 的表对应的 Java 类: ```java package com.example.demo.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // Getters and Setters } ``` 此代码片段展示了如何利用 JPA 注解声明持久化对象及其字段映射关系[^3]。 --- #### 编写 Repository 接口 通过继承 `JpaRepository<T, ID>` 提供基本 CRUD 方法的支持: ```java package com.example.demo.repository; import com.example.demo.entity.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { } ``` 这样即可获得内置的操作方法而无需额外编码逻辑处理细节部分[^4]。 --- #### 测试运行 最后,在主应用程序入口处启动服务并测试功能是否正常工作: ```java package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 至此完成了整个流程介绍从环境搭建到具体实践操作步骤说明完毕。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值