Spring Boot开启之路——使用JPA获取数据

一、Spring初始化工作

1、打开https://start.spring.io/,在此页面填写项目相关信息,并添加相应依赖,然后点“GENERATE”,便可生成zip文件,在自己电脑合适位置解压,再使用IDEA打开这个项目。

二、相关文件编写

     想要实现的效果:将顾客信息(包含id,firstname, lastname)存储到H2数据库中,并可以获取数据库中所有顾客信息、以及根据顾客ID、lastname获取顾客信息。具体实现如下:

1、定义一个简单的Entity:在src/main/java/com/example/accessingdatajpa目录下创建一个Customer类,该Customer.java代码如下:

package com.example.accessingdatajpa;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

//该注解表示Customer是一个JPA实体,也就是说会将Customer映射成一张名为Customer的表
@Entity
public class Customer {

  //该注解意在让JPA知道id属性是实体的ID
  @Id
  //该注解表示ID为自动加1
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private String firstName;
  private String lastName;

  //JPA需要一个默认构造函数
  protected Customer() {}

  //这个构造函数才是我们用来创造Customer实例的
  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  //重写该方法,使得其能按照特定格式输出Customer属性
  public String toString() {
    return String.format(
        "Customer[id=%d, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

  public Long getId() {
    return id;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }
}

 2、创建一个简单的查询:在“src/main/java/com/example/accessingdatajpa/”目录下创建一个CustomerRepository接口

package com.example.accessingdatajpa;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<Customer, Long> {

  List<Customer> findByLastName(String lastName);

  Customer findById(long id);
}

解释:Spring Data JPA可以使用JPA将数据存储到关系型数据库中,最显著的特点是在运行时为repository接口自动创建其实现类(不需要自己写该接口的实现类)。CustomerRepository继承自CrudRepository,所以该接口含有save、delete、find相关方法。而且你可以自定义其他查询的方法,只需在接口内声明该方法,比如代码中的findByLastName()方法。

3、创建一个应用类:在初始化阶段Spring Boot创建了一个AccessingDataJpaApplication类,其具体代码如下:

package com.example.accessingdatajpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//该注解表示该类是个SpringBoot应用
@SpringBootApplication
public class AccessingDataJpaApplication {

  public static void main(String[] args) {
    //使用该方法启动SpringBoot应用
    SpringApplication.run(AccessingDataJpaApplication.class, args);
  }

  @Bean
  public CommandLineRunner demo(CustomerRepository repository) {
    return (args) -> {
      // save a few customers
      repository.save(new Customer("Jack", "Bauer"));
      repository.save(new Customer("Chloe", "O'Brian"));
      repository.save(new Customer("Kim", "Bauer"));
      repository.save(new Customer("David", "Palmer"));
      repository.save(new Customer("Michelle", "Dessler"));

      // fetch all customers
      log.info("Customers found with findAll():");
      log.info("-------------------------------");
      for (Customer customer : repository.findAll()) {
        log.info(customer.toString());
      }
      log.info("");

      // fetch an individual customer by ID
      Customer customer = repository.findById(1L);
      log.info("Customer found with findById(1L):");
      log.info("--------------------------------");
      log.info(customer.toString());
      log.info("");

      // fetch customers by last name
      log.info("Customer found with findByLastName('Bauer'):");
      log.info("--------------------------------------------");
      repository.findByLastName("Bauer").forEach(bauer -> {
        log.info(bauer.toString());
      });
      // for (Customer bauer : repository.findByLastName("Bauer")) {
      //  log.info(bauer.toString());
      // }
      log.info("");
    };
  }

}

解释:demo方法,首先它会从Spring应用上下文环境中获取CustomerRepository,然后将顾客信息存储到数据库中,接着你可根据一些方法来获取你想要的顾客信息。demo返回一个CommandLineRunner bean,它在应用启动时会自动运行其代码。

猜你喜欢

转载自blog.csdn.net/buer219/article/details/106635673
今日推荐