Springboot使用JPA访问数据

本指南将引导您构建一个使用SpringDataJPA在关系数据库中存储和检索数据的应用程序。

你将要建什么

您将在基于内存的数据库中构建一个存储Customer的POJO(Plain Ordinary Java Object,简单的Java对象,实际就是普通JavaBeans)。

你需要什么

如何完成本指南

像大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,你最终都会得到工作代码。

从头开始用Gradle建造.

跳过基础,做以下工作:

当你完成以后,你可以在gs-accessing-data-jpa/complete中的代码中检查结果.

用Gradle建造

首先,您需要设置一个基本的构建脚本。在使用Spring构建应用程序时,您可以使用任何您喜欢的构建系统,但是您需要使用的代码 Gradle和 Maven。如果你对两者都不熟悉,请参考用Gradle构建Java项目使用Maven构建Java项目.

创建目录结构

在您选择的项目目录中,创建以下子目录结构;例如,使用mkdir -p src/main/java/hello关于*nix系统:

└── src
    └── main
        └── java
            └── hello

创建一个Gradle构建文件

下面是初始的Gradle构建文件.

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-accessing-data-jpa'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
    maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("com.h2database:h2")
    testCompile("junit:junit")
}

SpringBoot的gradle插件提供了许多方便的功能:

  • 它收集类路径上的所有JAR,并构建一个可运行的“über-jar”,这使得执行和传输服务更加方便。

  • 它搜索public static void main()方法标记为可运行的类。

  • 它提供了一个内置的依赖项解析器,它将版本号设置为匹配SpringBoot依赖关系。您可以覆盖任何版本,但它将默认为Boot所选的一组版本。

用Maven构建

首先,您需要设置一个基本的构建脚本。在使用Spring构建应用程序时,您可以使用任何您喜欢的工具构建系统,但是这里您需要使用Maven。如果您不熟悉Maven,请参阅使用Maven构建Java项目.

创建目录结构

在您选择的项目目录中,创建以下子目录结构;例如,使用mkdir -p src/main/java/hello关于*nix系统:

└── src
    └── main
        └── java
            └── hello

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-accessing-data-jpa</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>

    <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>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Spring Boot Maven插件提供了许多方便的功能:

  • 它收集类路径上的所有JAR,并构建一个可运行的“über-jar”,这使得执行和传输服务更加方便。

  • 它搜索public static void main()方法标记为可运行的类。

  • 它提供了一个内置的依赖项解析器,它将版本号设置为匹配SpringBoot依赖关系。您可以覆盖任何版本,但它将默认为Boot所选的一组版本。

用IDE构建

 

 

定义一个简单的实体

在本例中,存储Customer对象,并将其注释为JPA实体。

src/main/java/hello/Customer.java

package hello;

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);
    }

}

这里你有一个Customer类具有三个属性,idfirstName,以及lastName。还有两个构造函数。默认构造函数的存在只是为了JPA。您不会直接使用它,因此它被指定为protected。另一个构造函数将用于创建Customer保存到数据库中。

 在本指南中,为了简洁起见,忽略了典型的getter和setter。

Customer类被注释为@Entity表示它是一个JPA实体。因为缺乏@Table注释,该实体将被映射到一个名为Customer的table.

Customerid属性注释为@Id以便JPA将其识别为对象的ID。id属性也用@GeneratedValue指示应该自动生成ID。

另外两个属性,firstNamelastName都没有注释。它们将映射到与属性本身同名的列。

toString()方法将打印出Customer的属性。

创建简单查询

SpringDataJPA侧重于使用JPA将数据存储在关系数据库中。它最引人注目的特性是能够在运行时从存储库(repository)接口自动创建存储库的实现(imlpementions)。

要了解它是如何工作的,请创建一个与Customer实体:

src/main/java/hello/CustomerRepository.java

package hello;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);
}

CustomerRepository继承CrudRepository接口。它使用的实体和ID的类型CustomerLong,CrudRepository的泛型参数中指定。通过继承CrudRepositoryCustomerRepository几种方法,包括保存、删除和查找的方法。用于操作Customer实体。

SpringDataJPA还允许您通过简单地声明方法签名来定义其他查询方法。如例子中CustomerRepositoryfindByLastName()方法。

在典型的Java应用程序中,您希望编写一个实现CustomerRepository。但这正是SpringDataJPA如此强大的原因:您不必编写存储库接口的实现。SpringDataJPA在运行应用程序时动态创建一个实现。

让我们把它连接起来,看看它是什么样子!

创建应用程序类

在这里,您将创建一个包含所有组件的应用程序类。

src/main/java/hello/Application.java

package hello;

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 Application {

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

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

	@Bean
	public CommandLineRunner demo(CustomerRepository repository) {
		return (args) -> {
			// save a couple of 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
			repository.findById(1L)
				.ifPresent(customer -> {
					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("");
		};
	}

}

@SpringBootApplication是一个方便的注释,它添加了以下所有内容:

  • @Configuration tags the class as a source of bean definitions for the application context.

  • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.

  • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

  • @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.

main()方法使用SpringBoot的SpringApplication.run()方法来启动应用程序。您注意到没有一行XML吗?也没有web.xml。这个Web应用程序是100%纯Java的,您不必处理任何配置问题。

Application包括main()方法,该方法将CustomerRepository通过几个测试。首先,它获取CustomerRepository来自Spring应用程序上下文。那就省下了一小撮Customer对象,演示save()方法并设置要处理的一些数据。接下来,它调用findAll()把所有Customer对象。然后它让findOne()根据它的ID去取一个Customer。最后,它调用findByLastName()找到所有姓“Bauer”的顾客。

 默认情况下,SpringBoot将启用JPA存储库支持,并查看包(及其子包)@SpringBootApplication找到了。如果配置中的JPA存储库接口定义位于不可见的包中,则可以使用@EnableJpaRepositories以及它的类型安全basePackageClasses=MyRepository.class参数。

构建一个可执行的JAR

您可以使用Gradle或Maven从命令行运行应用程序。或者,您可以构建一个包含所有必需的依赖项、类和资源的单个可执行JAR文件,并运行该文件。这使得在整个开发生命周期、跨不同环境等将服务作为应用程序进行发布、版本和部署变得非常容易。

如果使用Gradle,则可以使用./gradlew bootRun。或者您可以使用./gradlew build。然后可以运行JAR文件:

java -jar build/libs/gs-accessing-data-jpa-0.1.0.jar

如果使用的是Maven,则可以使用./mvnw spring-boot:run。或者您可以用./mvnw clean package。然后可以运行JAR文件:

java -jar target/gs-accessing-data-jpa-0.1.0.jar
 上面的过程将创建一个可运行的JAR。相反你也可以选择构建一个经典的WAR文件

你应该看到这样的东西:

== Customers found with findAll():
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=2, firstName='Chloe', lastName='O'Brian']
Customer[id=3, firstName='Kim', lastName='Bauer']
Customer[id=4, firstName='David', lastName='Palmer']
Customer[id=5, firstName='Michelle', lastName='Dessler']

== Customer found with findOne(1L):
Customer[id=1, firstName='Jack', lastName='Bauer']

== Customer found with findByLastName('Bauer'):
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=3, firstName='Kim', lastName='Bauer']

摘要

祝贺你!您已经编写了一个简单的应用程序,它使用SpringDataJPA将对象保存到数据库中并获取它们-所有这些都没有编写具体的存储库实现。

 如果您对使用基于超媒体的RESTful前端公开JPA存储库感兴趣,那么您可能需要阅读使用REST访问JPA数据.

另见

下列指南也可能有帮助:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值