Git Product home page Git Product logo

gs-accessing-data-jpa's Introduction

This guide walks you through the process of building an application that uses Spring Data JPA to store and retrieve data in a relational database.

What You Will Build

You will build an application that stores Customer POJOs (Plain Old Java Objects) in a memory-based database.

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Spring Data JPA and then H2 Database.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
Note
You can also fork the project from Github and open it in your IDE or other editor.

Define a Simple Entity

In this example, you store Customer objects, each annotated as a JPA entity. The following listing shows the Customer class (in src/main/java/com/example/accessingdatajpa/Customer.java):

link:complete/src/main/java/com/example/accessingdatajpa/Customer.java[role=include]

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.

Create Simple Queries

Spring Data JPA focuses on using JPA to store data in a relational database. Its most compelling feature is the ability to create repository implementations automatically, at runtime, from a repository interface.

To see how this works, create a repository interface that works with Customer entities as the following listing (in src/main/java/com/example/accessingdatajpa/CustomerRepository.java) shows:

link:complete/src/main/java/com/example/accessingdatajpa/CustomerRepository.java[role=include]

CustomerRepository extends the CrudRepository interface. The type of entity and ID that it works with, Customer and Long, are specified in the generic parameters on CrudRepository. By extending CrudRepository, CustomerRepository inherits several methods for working with Customer persistence, including methods for saving, deleting, and finding Customer entities.

Spring Data JPA also lets you define other query methods by declaring their method signature. For example, CustomerRepository includes the findByLastName() method.

In a typical Java application, you might expect to write a class that implements CustomerRepository. However, that is what makes Spring Data JPA so powerful: You need not write an implementation of the repository interface. Spring Data JPA creates an implementation when you run the application.

Now you can wire up this example and see what it looks like!

Create an Application Class

Spring Initializr creates a simple class for the application. The following listing shows the class that Initializr created for this example (in src/main/java/com/example/accessingdatajpa/AccessingDataJpaApplication.java):

link:initial/src/main/java/com/example/accessingdatajpa/AccessingDataJpaApplication.java[role=include]

Now you need to modify the simple class that the Initializr created for you. To get output (to the console, in this example), you need to set up a logger. Then you need to set up some data and use it to generate output. The following listing shows the finished AccessingDataJpaApplication class (in src/main/java/com/example/accessingdatajpa/AccessingDataJpaApplication.java):

link:complete/src/main/java/com/example/accessingdatajpa/AccessingDataJpaApplication.java[role=include]

The AccessingDataJpaApplication class includes a demo() method that puts the CustomerRepository through a few tests. First, it fetches the CustomerRepository from the Spring application context. Then it saves a handful of Customer objects, demonstrating the save() method and setting up some data to work with. Next, it calls findAll() to fetch all Customer objects from the database. Then it calls findById() to fetch a single Customer by its ID. Finally, it calls findByLastName() to find all customers whose last name is "Bauer". The demo() method returns a CommandLineRunner bean that automatically runs the code when the application launches.

Note
By default, Spring Boot enables JPA repository support and looks in the package (and its subpackages) where @SpringBootApplication is located. If your configuration has JPA repository interface definitions located in a package that is not visible, you can point out alternate packages by using @EnableJpaRepositories and its type-safe basePackageClasses=MyRepository.class parameter.

When you run your application, you should see output similar to the following:

== 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 findById(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']

Summary

Congratulations! You have written a simple application that uses Spring Data JPA to save objects to and fetch them from a database, all without writing a concrete repository implementation.

Note
If you want to expose JPA repositories with a hypermedia-based RESTful front end with little effort, you might want to read Accessing JPA Data with REST.

gs-accessing-data-jpa's People

Contributors

0scvr avatar alyssais avatar bclozel avatar bert-r avatar brandontoups avatar btalbott avatar buzzardo avatar cbeams avatar georgepanaretos avatar gregturn avatar habuma avatar jpgough avatar mhuisman avatar odrotbohm avatar prmr avatar robertmcnees avatar royclarkson avatar sebastianaigner avatar spring-operator avatar wangzitiansky avatar wilkinsona avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gs-accessing-data-jpa's Issues

Additional H2 configuration info.

Does h2 has implicit configuration? I didn't found h2 user/password and any other configuration in example?
It would be useful to add following (later found) explanation from spring boot docs:

Spring Boot can auto-configure embedded H2, HSQL, and Derby databases. You need not provide any connection URLs. You need only include a build dependency to the embedded database that you want to use.

org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC

Using

  • spring-boot + spring-boot-JPA 2.1.3 (HikariCP 3.2)
  • Oracle Java 8
  • MySQL driver 8.0.15
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:109) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:136) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:47) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1984) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1914) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1892) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:937) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2689) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2672) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.Loader.list(Loader.java:2501) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:395) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1508) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1537) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.query.Query.getResultList(Query.java:135) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:129) ~[spring-data-jpa-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91) ~[spring-data-jpa-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136) ~[spring-data-jpa-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125) ~[spring-data-jpa-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
... 76 common frames omitted
     Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.
at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:676) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:190) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:155) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:128) ~[HikariCP-3.2.0.jar!/:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:106) ~[hibernate-core-5.3.7.Final.jar!/:5.3.7.Final]
... 111 common frames omitted

according to different post / page looks like some connection are not closing properly.

I am just extending from
org.springframework.data.repository.CrudRepository

public interface XxxRepository extends CrudRepository<Xxx, Long> {

@Query("SELECT x FROM Xxx x WHERE x.id = ?1 AND x.idType = ?2 AND x.mycode = ?3 and x.isActive = true")
   List<Xxx> find(String id, String type, String cmyode);
}

So, no idea how to force close connections.

I tried to increase the pool size:
spring.datasource.hikari.maximum-pool-size=21

but didn't solve the issue.

I had default settings for hiraki

 : HikariPool-1 - configuration:
          : allowPoolSuspension.............false
          : autoCommit......................true
          : catalog.........................none
          : connectionInitSql...............none
          : connectionTestQuery.............none
          : connectionTimeout...............30000
          : dataSource......................none
          : dataSourceClassName.............none
          : dataSourceJNDI..................none
          : dataSourceProperties............{password=<masked>}
          : driverClassName................."com.mysql.cj.jdbc.Driver"
          : healthCheckProperties...........{}
          : healthCheckRegistry.............none
          : idleTimeout.....................600000
          : initializationFailTimeout.......1
          : isolateInternalQueries..........false
          : jdbcUrl.........................jdbc:mysql://127.0.0.1:3306/xxx?verifyServerCertificate=false&useSSL=true&serverTimezone=UTC&serverTimezone=UTC
          : leakDetectionThreshold..........0
          : maxLifetime.....................1800000
          : maximumPoolSize.................21
          : metricRegistry..................none
          : metricsTrackerFactory...........none
          : minimumIdle.....................21
          : password........................<masked>
          : poolName........................"HikariPool-1"
          : readOnly........................false
          : registerMbeans..................false
          : scheduledExecutor...............none
          : schema..........................none
          : threadFactory...................internal
          : transactionIsolation............default
          : username........................"mservice"
          : validationTimeout...............5000

Any clue / suggestion / tuning ?

Code doesn't show in the "Accessing data with JPA" learning guide

Apologies if this is the wrong place to submit this docs issue, but i couldn't find any instructions on where and how to submit this issue on the spring.io site:
on the learning guide page: https://spring.io/guides/gs/accessing-data-jpa/
All the code errors out with the following:

Unresolved directive in - include::complete/pom.xml[]
Unresolved directive in - include::complete/src/main/java/com/example/accessingdatajpa/Customer.java[]

etc.

Originally reported at spring-projects/spring-data-jpa#2142 by @nthali.

Typo in Accessing Data JPA guide

Hello!

There is a typo in the guide Getting Started | Accessing Data with JPA.
After the code for AccessingDataJpaApplication.java, you mentioned that it calls findOne() to fetch a single Customer by its ID., but it should be findById() instead.

findOneById

Document text repeated

https://spring.io/guides/gs/accessing-data-jpa/
https://github.com/spring-guides/gs-accessing-data-jpa

At above two place, please search "First, it fetches", and you can find the repeated text:
First, it fetches the CustomerRepository from the Spring application context. Then it saves a handful of Customer objects, demonstrating the save() method and setting up some data to use. Next, it calls findAll() to fetch all Customer objects from the database. Then it calls findOne() to fetch a single Customer by its ID. Finally, it calls findByLastName() to find all customers whose last name is "Bauer".

Cannot access com.example.accessingdatajpa.Customer

I use maven to open the file pom.xml to build the project. And everything is ok but Cannot access com.example.accessingdatajpa.Customer
It seems that interface CustomerRepository extends CrudRepository<Customer, Long> can not access com.example.accessingdatajpa.Customer.
Screenshot 2021-12-01 201640

OS:
Windows 10 64bit

Intellij IDEA version:
Intellij IDEA ultimate 2021.1

Apache-maven version:
Apache-maven-3.8.1

ClassNotFound issue on clean checked out project

I downloaded latest version from master.
Both "mvnw spring-boot:run" and "mvnw clean package" are failing with same error "mvnw clean package -Dmaven.test.skip=true" succeed so JAR is being build but same exception occurs when running with java -jar target/gs-accessing-data-jpa-0.1.0.jar

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

2016-09-07 22:35:57.704  INFO 9948 --- [           main] hello.Application                        : Starting Application v0.1.0 on DESKTOP-C6DUQ9V with PID 9948 (C:\workspace\projects\spring-tutorial\gs-accessing-data-jpa-master\complete\target\gs-accessing-data-jpa-0.1.0.jar started by mail in C:\workspace\projects\spring-tutorial\gs-accessing-data-jpa-master\complete)
2016-09-07 22:35:57.709  INFO 9948 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
2016-09-07 22:35:57.798  INFO 9948 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@22d8cfe0: startup date [Wed Sep 07 22:35:57 CEST 2016]; root of context hierarchy
2016-09-07 22:35:58.752 ERROR 9948 --- [           main] o.s.boot.SpringApplication               : Application startup failed

java.lang.NoClassDefFoundError: org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor
        at org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension.<clinit>(JpaRepositoryConfigExtension.java:65) ~[spring-data-jpa-1.10.2.RELEASE.jar!/:na]
        at org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfigureRegistrar.getRepositoryConfigurationExtension(JpaRepositoriesAutoConfigureRegistrar.java:49) ~[spring-boot-autoconfigure-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.registerBeanDefinitions(AbstractRepositoryConfigurationSourceSupport.java:60) ~[spring-boot-autoconfigure-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:352) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:143) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:333) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523) ~[spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at hello.Application.main(Application.java:17) [classes!/:0.1.0]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_102]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_102]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_102]
        at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_102]
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [gs-accessing-data-jpa-0.1.0.jar:0.1.0]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [gs-accessing-data-jpa-0.1.0.jar:0.1.0]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [gs-accessing-data-jpa-0.1.0.jar:0.1.0]
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:58) [gs-accessing-data-jpa-0.1.0.jar:0.1.0]
Caused by: java.lang.ClassNotFoundException: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
        at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.8.0_102]
        at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.8.0_102]
        at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_102]
        at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_102]
        at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_102]
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:89) ~[gs-accessing-data-jpa-0.1.0.jar:0.1.0]
        at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_102]
        ... 26 common frames omitted
Caused by: java.util.zip.ZipException: invalid code lengths set
        at java.util.zip.InflaterInputStream.read(Unknown Source) ~[na:1.8.0_102]
        at org.springframework.boot.loader.jar.ZipInflaterInputStream.read(ZipInflaterInputStream.java:52) ~[gs-accessing-data-jpa-0.1.0.jar:0.1.0]
        at sun.misc.Resource.getBytes(Unknown Source) ~[na:1.8.0_102]
        at java.net.URLClassLoader.defineClass(Unknown Source) ~[na:1.8.0_102]
        at java.net.URLClassLoader.access$100(Unknown Source) ~[na:1.8.0_102]
        ... 33 common frames omitted

2016-09-07 22:35:58.756  INFO 9948 --- [           main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@22d8cfe0: startup date [Wed Sep 07 22:35:57 CEST 2016]; root of context hierarchy
2016-09-07 22:35:58.759  WARN 9948 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception thrown from LifecycleProcessor on context close

java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.context.annotation.AnnotationConfigApplicationContext@22d8cfe0: startup date [Wed Sep 07 22:35:57 CEST 2016]; root of context hierarchy
        at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:416) [spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:997) [spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:956) [spring-context-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:815) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.4.0.RELEASE.jar!/:1.4.0.RELEASE]
        at hello.Application.main(Application.java:17) [classes!/:0.1.0]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_102]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_102]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_102]
        at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_102]
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [gs-accessing-data-jpa-0.1.0.jar:0.1.0]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [gs-accessing-data-jpa-0.1.0.jar:0.1.0]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [gs-accessing-data-jpa-0.1.0.jar:0.1.0]
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:58) [gs-accessing-data-jpa-0.1.0.jar:0.1.0]

Spec:
Java version: Java 8 build 102
OS: Windows 10

Dependency tree:

[INFO] org.springframework:gs-accessing-data-jpa:jar:0.1.0
[INFO] +- org.springframework.boot:spring-boot-starter-data-jpa:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.4.0.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.1.7:compile
[INFO] |  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.7:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.21:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.21:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.17:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-aop:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-aop:jar:4.3.2.RELEASE:compile
[INFO] |  |  \- org.aspectj:aspectjweaver:jar:1.8.9:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-jdbc:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat:tomcat-jdbc:jar:8.5.4:compile
[INFO] |  |  |  \- org.apache.tomcat:tomcat-juli:jar:8.5.4:compile
[INFO] |  |  \- org.springframework:spring-jdbc:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.hibernate:hibernate-core:jar:5.0.9.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  |  +- org.javassist:javassist:jar:3.20.0-GA:compile
[INFO] |  |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  |  +- org.jboss:jandex:jar:2.0.0.Final:compile
[INFO] |  |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  |  \- xml-apis:xml-apis:jar:1.4.01:compile
[INFO] |  |  \- org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final:compile
[INFO] |  +- org.hibernate:hibernate-entitymanager:jar:5.0.9.Final:compile
[INFO] |  +- javax.transaction:javax.transaction-api:jar:1.2:compile
[INFO] |  +- org.springframework.data:spring-data-jpa:jar:1.10.2.RELEASE:compile
[INFO] |  |  +- org.springframework.data:spring-data-commons:jar:1.12.2.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-orm:jar:4.3.2.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-context:jar:4.3.2.RELEASE:compile
[INFO] |  |  |  \- org.springframework:spring-expression:jar:4.3.2.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-tx:jar:4.3.2.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-beans:jar:4.3.2.RELEASE:compile
[INFO] |  |  +- org.slf4j:slf4j-api:jar:1.7.21:compile
[INFO] |  |  \- org.slf4j:jcl-over-slf4j:jar:1.7.21:compile
[INFO] |  \- org.springframework:spring-aspects:jar:4.3.2.RELEASE:compile
[INFO] +- com.h2database:h2:jar:1.4.192:compile
[INFO] \- org.springframework.boot:spring-boot-starter-test:jar:1.4.0.RELEASE:test
[INFO]    +- org.springframework.boot:spring-boot-test:jar:1.4.0.RELEASE:test
[INFO]    +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.4.0.RELEASE:test
[INFO]    +- com.jayway.jsonpath:json-path:jar:2.2.0:test
[INFO]    |  \- net.minidev:json-smart:jar:2.2.1:test
[INFO]    |     \- net.minidev:accessors-smart:jar:1.1:test
[INFO]    |        \- org.ow2.asm:asm:jar:5.0.3:test
[INFO]    +- junit:junit:jar:4.12:test
[INFO]    +- org.assertj:assertj-core:jar:2.5.0:test
[INFO]    +- org.mockito:mockito-core:jar:1.10.19:test
[INFO]    |  \- org.objenesis:objenesis:jar:2.1:test
[INFO]    +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO]    +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO]    +- org.skyscreamer:jsonassert:jar:1.3.0:test
[INFO]    |  \- org.json:json:jar:20140107:test
[INFO]    +- org.springframework:spring-core:jar:4.3.2.RELEASE:compile
[INFO]    \- org.springframework:spring-test:jar:4.3.2.RELEASE:test
[INFO] ------------------------------------------------------------------------`

Convert to Spring Boot

I'm not sure that leaving out Spring Boot from this guide helps users (especially the ones that want to "get started", which is what the guide is supposed to be about). Maybe if we think users need to know about transaction managers and entity manager factor beans we could include a link at the end to the relevant Boot config file.

example code fails to run with maven

My steps:

  1. downloaded the code, extracted to C:\tmp
  2. Open command prompt, ran the following commands from the "complete" folder
    Maven command: mvnw spring-boot:run > maven-log.txt
    Gradle command: gradlew bootRun > gradle-log.txt

the logs are attached.
the maven execution fails with: "No qualifying bean of type 'hello.CustomerRepository' available"

I have JAVA_HOME set to JDK 1.8, and have the JDK and maven 3.3 in my PATH.
Am I doing something wrong?

gradle-log.txt
maven-log.txt

Unresolved directive in <stdin>

Hello, when I wanted to read the guide, there was no code in the examples, but the following error message: Unresolved directive in - include::complete/pom.xml[]
Please fix the bug.

Update the Spring Boot version

An ongoing task is to keep the Spring Boot version current in the build files:

To do so, update the following files:

complete/build.gradle
complete/pom.xml
initial/build.gradle
initial/pom.xml

Getting error entityManagerFactory not found


APPLICATION FAILED TO START


Description:

Parameter 0 of method demo in hello.Application required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

In Application Class repository.findById(1L) method is undefined

Hi
(I am not good at English before I ask you a question.)

I'm practicing this project. (https://spring.io/guides/gs/accessing-data-jpa/)
but i try to this project, I'm in trouble.

repository.findById(1L)
.ifPresent(customer -> {
        log.info("Customer found with findById(1L):");
	log.info("--------------------------------");
	log.info(customer.toString());
	log.info("");
});

my problem is
repository.findById(1L) method is undefined

how to solve this problem??

'org.springframework.' is an invalid name on this platform

I import "completed" into the latetest version of STS. (I did this while at 2013 Spring 2GX while sitting in audiance of spring.io talk). pom.xml shows this error within STS:

'org.springframework.' is an invalid name on this platform. (org.apache.maven.plugins:maven-jar-plugin:2.4:jar:default-jar:package)

The error pointer in STS is pointing to this entry:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>0.5.0.M2</version>
</parent>

Not working in 1.5.2

I got this error while running the complete:
Parameter 0 of method demo in com.example.DemoApplication required a bean of type 'com.example.CustomerRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.CustomerRepository' in your configuration.

So, i change spring boot version back to 1.4.4 and it works.

Update Spring Boot to the latest version

Update the guide to use the most recent Spring Boot version.

Files that require changes are:

initial/build.gradle
initial/pom.xml
complete/build.gradle
complete/pom.xml

Clean up some of the language

"Finally, Application includes a main() method that puts the CustomerRepository through a few tests. First, it fetches the CustomerRepository from the Spring application context. Then it saves a handful of Customer objects, demonstrating the save() method and setting up some data to work with. Next, it calls findAll() to fetch all Customer objects from the database. Then it calls findOne() to fetch a single Customer by its ID. Finally, it calls findByLastName() to find all customers whose last name is "Bauer"."

This prose starts with "finally" and has "finally" in the last sentence.

Accessing Data with JPA article needs improvements

The startup guide at Accessing Data with JPA requires some improvements. For example, there is no place for this paragraph in the write-up:

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.

This is because that write-up is not about serving HTTP requests. It has nothing to do with serving content to the user. And there is no Spring boot starter web dependency on the classpath of the article.

Instead, it should be replaced with something like this:

Spring boot application will automatically enable @EnableJpaRepositories if it finds spring-boot-starter-data-mongodb on the classpath.

Something like that.

spring-boot-gradle-plugin:2.0.5.RELEASE problem with JDK 11

Hi
Problem: spring-boot-gradle-plugin:2.0.5.RELEASE won't work with JDK 11.
Error: Process 'command 'C:\Program Files\Java\jdk-11.0.1\bin\java.exe'' finished with non-zero exit value 1
Solution: After setting to 2.1.2.RELEASE it works fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.