Demo project for Spring Boot 【1】spring-boot-starter【2】Accessing Data with JPA

Here you have a Customer class with three attributes: id, firstName, and lastName. You also have two constructors. The default constructor exists only for the sake of JPA. You do not use it directly, so it is designated as protected. The other constructor is the one you use to create instances of Customer to be saved to the database.
The Customer class is annotated with @Entity, indicating that it is a JPA entity. (Because no @Table annotation exists, it is assumed that this entity is mapped to a table named Customer.)
The Customer object’s id property is annotated with @Id so that JPA recognizes it as the object’s ID. The id property is also annotated with @GeneratedValue to indicate that the ID should be generated automatically.
The other two properties, firstName and lastName, are left unannotated. It is assumed that they are mapped to columns that share the same names as the properties themselves.
The convenient toString() method print outs the customer’s properties.

这里有一个Customer类,它有三个属性:id、firstName和lastName。您还有两个构造函数。默认构造函数的存在只是为了JPA。您不直接使用它,所以它被指定为受保护的。另一个构造函数是用于创建要保存到数据库中的Customer实例的构造函数。
Customer类用@Entity注释,表明它是一个JPA实体。(由于不存在@Table注释,因此假定此实体映射到名为Customer的表。)
Customer对象的id属性用@id注释,以便JPA将其识别为对象的id。id属性也用@GeneratedValue进行注释,以指示应该自动生成id。
其他两个属性,firstName和lastName没有注释。假设它们被映射到与属性本身同名的列。
方便的toString()方法打印出客户的属性。

Demo project for Spring Boot 【1】spring-boot-starter【2】Accessing Data with JPA_第1张图片

package com.example.accessingdatajpa;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class AccessingDataJpaApplication {

  private static final Logger log = LoggerFactory.getLogger(AccessingDataJpaApplication.class);

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataJpaApplication.class);
  }

  @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("");
    };
  }

}
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);
}
package com.example.accessingdatajpa;

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

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private String firstName;
  private String lastName;

  protected Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  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;
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo-JPA</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo-JPA</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

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

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.2.RELEASE)

2020-08-07 14:04:54.790  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Starting AccessingDataJpaApplication on PC-202008012041 with PID 16784 (G:\eclipse-workspace-Jee\demo-JPA\target\classes started by Administrator in G:\eclipse-workspace-Jee\demo-JPA)
2020-08-07 14:04:54.793  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : No active profile set, falling back to default profiles: default
2020-08-07 14:04:55.173  INFO 16784 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-08-07 14:04:55.223  INFO 16784 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 43ms. Found 1 JPA repository interfaces.
2020-08-07 14:04:55.575  INFO 16784 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-07 14:04:55.582  INFO 16784 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-08-07 14:04:55.674  INFO 16784 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-08-07 14:04:55.715  INFO 16784 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-08-07 14:04:55.753  INFO 16784 --- [         task-1] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.18.Final
2020-08-07 14:04:55.802  INFO 16784 --- [           main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-08-07 14:04:55.882  INFO 16784 --- [         task-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-08-07 14:04:55.984  INFO 16784 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-08-07 14:04:56.504  INFO 16784 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-08-07 14:04:56.513  INFO 16784 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-07 14:04:56.702  INFO 16784 --- [           main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-08-07 14:04:56.708  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Started AccessingDataJpaApplication in 2.208 seconds (JVM running for 4.685)
2020-08-07 14:04:56.754  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customers found with findAll():
2020-08-07 14:04:56.754  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : -------------------------------
2020-08-07 14:04:56.840  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer[id=1, firstName='Jack', lastName='Bauer']
2020-08-07 14:04:56.840  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer[id=2, firstName='Chloe', lastName='O'Brian']
2020-08-07 14:04:56.840  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer[id=3, firstName='Kim', lastName='Bauer']
2020-08-07 14:04:56.840  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer[id=4, firstName='David', lastName='Palmer']
2020-08-07 14:04:56.841  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer[id=5, firstName='Michelle', lastName='Dessler']
2020-08-07 14:04:56.841  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : 
2020-08-07 14:04:56.849  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer found with findById(1L):
2020-08-07 14:04:56.850  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : --------------------------------
2020-08-07 14:04:56.850  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer[id=1, firstName='Jack', lastName='Bauer']
2020-08-07 14:04:56.850  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : 
2020-08-07 14:04:56.850  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer found with findByLastName('Bauer'):
2020-08-07 14:04:56.850  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : --------------------------------------------
2020-08-07 14:04:56.878  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer[id=1, firstName='Jack', lastName='Bauer']
2020-08-07 14:04:56.878  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : Customer[id=3, firstName='Kim', lastName='Bauer']
2020-08-07 14:04:56.878  INFO 16784 --- [           main] c.e.a.AccessingDataJpaApplication        : 
2020-08-07 14:05:56.708  INFO 16784 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-08-07 14:05:56.709  INFO 16784 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-08-07 14:05:56.715  INFO 16784 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-08-07 14:05:56.715  INFO 16784 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-08-07 14:05:56.722  INFO 16784 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Demo project for Spring Boot 【1】spring-boot-starter【2】Accessing Data with JPA_第2张图片Demo project for Spring Boot 【1】spring-boot-starter【2】Accessing Data with JPA_第3张图片

你可能感兴趣的:(JPA,springboot,jpa,java)