java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot2.3.0配置JPA

SpringBoot2.3.0配置JPA的实现示例

作者:DeadAndLive

这篇文章主要介绍了SpringBoot2.3.0配置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);
  }
}

测试

注意:

查询所有

插入

到此这篇关于SpringBoot2.3.0配置JPA的实现示例的文章就介绍到这了,更多相关SpringBoot2.3.0配置JPA内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文