亲宝软件园·资讯

展开

SpringBoot2.3.0配置JPA SpringBoot2.3.0配置JPA的实现示例

DeadAndLive 人气:0
想了解SpringBoot2.3.0配置JPA的实现示例的相关内容吗,DeadAndLive在本文为您仔细讲解SpringBoot2.3.0配置JPA的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringBoot2.3.0配置JPA,SpringBoot,配置JPA,下面大家一起来学习吧。

JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<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.yml

spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

spring.jpa.database

spring:
 datasource:
  driver-class-name: com.mysql.cj.jdbc.Driver
  url: jdbc:mysql://localhost:3306/spring_boot?serverTimezone=GMT%2B8
  username: root
  password: root
 jpa:
  hibernate:
   ddl-auto: update
  show-sql: true
  database: mysql

POJO

import lombok.Data;

import javax.persistence.*;

@Entity
@Table(name = "jpa_user")
@Data
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;
  @Column(name = "jpa_username",length = 40)
  private String username;
  @Column(name = "jpa_password")
  private String password;

}

Repository

JpaRepository的继承关系

所以继承JpaRepository

package com.live.repository;

import com.live.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User,Integer> {
}

Controller(测试)

@Autowired @Autowired
 UserRepository userRepository;
package com.live.controller;

import com.live.model.User;
import com.live.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
public class UserJPAController {

  @Autowired
  UserRepository userRepository;

  @GetMapping("/findAll")
  public List<User> findAll() {
    return userRepository.findAll();
  }

  @GetMapping("/findOne/{id}")
  public Optional<User> findOne(@PathVariable(value = "id") Integer id) {
    return userRepository.findById(id);
  }

  @GetMapping("/insert")
  public User insertOne(User user) {
    return userRepository.save(user);
  }
}

测试

注意:

查询所有

插入

加载全部内容

相关教程
猜你喜欢
用户评论