Simplifies the development of creating a JPA-based data access layer.

Overview

Spring Data JPA Spring Data JPA

Spring Data JPA icon?job=spring data jpa%2Fmain&subject=Build Gitter

Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.

Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.

Features

  • Implementation of CRUD methods for JPA Entities

  • Dynamic query generation from query method names

  • Transparent triggering of JPA NamedQueries by query methods

  • Implementation domain base classes providing basic properties

  • Support for transparent auditing (created, last changed)

  • Possibility to integrate custom repository code

  • Easy Spring integration with custom namespace

Code of Conduct

This project is governed by the Spring Code of Conduct. By participating, you are expected to uphold this code of conduct. Please report unacceptable behavior to [email protected].

Getting Started

Here is a quick teaser of an application using Spring Data Repositories in Java:

public interface PersonRepository extends CrudRepository<Person, Long> {

  List<Person> findByLastname(String lastname);

  List<Person> findByFirstnameLike(String firstname);
}

@Service
public class MyService {

  private final PersonRepository repository;

  public MyService(PersonRepository repository) {
    this.repository = repository;
  }

  public void doWork() {

    repository.deleteAll();

    Person person = new Person();
    person.setFirstname("Oliver");
    person.setLastname("Gierke");
    repository.save(person);

    List<Person> lastNameResults = repository.findByLastname("Gierke");
    List<Person> firstNameResults = repository.findByFirstnameLike("Oli*");
 }
}

@Configuration
@EnableJpaRepositories("com.acme.repositories")
class AppConfig {

  @Bean
  public DataSource dataSource() {
    return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
  }

  @Bean
  public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
    return new JpaTransactionManager(emf);
  }

  @Bean
  public JpaVendorAdapter jpaVendorAdapter() {
    HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
    jpaVendorAdapter.setDatabase(Database.H2);
    jpaVendorAdapter.setGenerateDdl(true);
    return jpaVendorAdapter;
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean lemfb = new LocalContainerEntityManagerFactoryBean();
    lemfb.setDataSource(dataSource());
    lemfb.setJpaVendorAdapter(jpaVendorAdapter());
    lemfb.setPackagesToScan("com.acme");
    return lemfb;
  }
}

Maven configuration

Add the Maven dependency:

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-jpa</artifactId>
  <version>${version}.RELEASE</version>
</dependency>

If you’d rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository and declare the appropriate dependency version.

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-jpa</artifactId>
  <version>${version}.BUILD-SNAPSHOT</version>
</dependency>

<repository>
  <id>spring-libs-snapshot</id>
  <name>Spring Snapshot Repository</name>
  <url>https://repo.spring.io/libs-snapshot</url>
</repository>

Getting Help

Having trouble with Spring Data? We’d love to help!

Reporting Issues

Spring Data uses GitHub as issue tracking system to record bugs and feature requests. If you want to raise an issue, please follow the recommendations below:

  • Before you log a bug, please search the issue tracker to see if someone has already reported the problem.

  • If the issue doesn’t exist already, create a new issue.

  • Please provide as much information as possible with the issue report, we like to know the version of Spring Data that you are using and JVM version, complete stack traces and any relevant configuration information.

  • If you need to paste code, or include a stack trace format it as code using triple backtick.

  • If possible try to create a test-case or project that replicates the issue. Attach a link to your code or a compressed file containing your code. Use an in-memory datatabase if possible or set the database up using Testcontainers.

Building from Source

You don’t need to build from source to use Spring Data (binaries in repo.spring.io), but if you want to try out the latest and greatest, Spring Data can be easily built with the maven wrapper. You also need JDK 1.8.

 $ ./mvnw clean install

If you want to build with the regular mvn command, you will need Maven v3.5.0 or above.

Also see CONTRIBUTING.adoc if you wish to submit pull requests, and in particular please sign the Contributor’s Agreement before your first non-trivial change.

Building reference documentation

Building the documentation builds also the project without running tests.

 $ ./mvnw clean install -Pdistribute

The generated documentation is available from target/site/reference/html/index.html.

Guides

The spring.io site contains several guides that show how to use Spring Data step-by-step:

Examples

License

Spring Data JPA is Open Source software released under the Apache 2.0 license.

Comments
  • No aliases found in result tuple [DATAJPA-885]

    No aliases found in result tuple [DATAJPA-885]

    ofbiz opened DATAJPA-885 and commented

    After migrating Spring Data application from Gosling-SR4 to Hopper-SR1 release, all custom queries that extends JpaRepository throws the following message:

    Caused by: java.lang.IllegalStateException: No aliases found in result tuple! Make sure your query defines aliases!
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter.convert(AbstractJpaQuery.java:246) [spring-data-jpa-1.10.1.RELEASE.jar:]
        at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:185) [spring-data-commons-1.12.1.RELEASE.jar:]
        at org.springframework.data.repository.query.ResultProcessor$ChainingConverter$1.convert(ResultProcessor.java:173) [spring-data-commons-1.12.1.RELEASE.jar:]
        at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:185) [spring-data-commons-1.12.1.RELEASE.jar:]
        at org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:142) [spring-data-commons-1.12.1.RELEASE.jar:]
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:107) [spring-data-jpa-1.10.1.RELEASE.jar:]
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:92) [spring-data-jpa-1.10.1.RELEASE.jar:]
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482) [spring-data-commons-1.12.1.RELEASE.jar:]
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460) [spring-data-commons-1.12.1.RELEASE.jar:]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
        ... 113 more
    
    public interface UserProfileAccessGroupRepository extends
            JpaRepository<UserProfileAccessGroup, UserProfileAccessGroupPK> {
    
        @Modifying
        @Query("DELETE FROM UserProfileAccessGroup upag WHERE upag.id.accessGroup = ?1")
        public void deleteByAccessGroup(AccessGroup accessGroup);
    
        @Modifying
        @Query("DELETE FROM UserProfileAccessGroup upag WHERE upag.id.userProfile = ?1")
        public void deleteByUserProfile(UserProfile userProfile);
    
        @Query("SELECT upag.id.accessGroup FROM UserProfileAccessGroup upag WHERE upag.id.userProfile = ?1")
        public List<AccessGroup> findAccessGroupByUserProfile(UserProfile userProfile);
    
        @Query("SELECT upag.id.accessGroup FROM UserProfileAccessGroup upag WHERE upag.id.userProfile = ?1 AND upag.id.accessGroup.functionality = false")
        public List<AccessGroup> findGroupByUserProfile(UserProfile userProfile);
    
        public List<UserProfileAccessGroup> findByExpirationDateBefore(Date date);
    }
    
    @Entity
    public class UserProfileAccessGroup implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @EmbeddedId
        private UserProfileAccessGroupPK id;
    
        private Date expirationDate;
    
        @ManyToOne
        @JoinColumn(name = "authorizedBy")
        private UserProfile authorizedBy;
    
        public UserProfileAccessGroupPK getId() {
    
            if (id == null) {
                id = new UserProfileAccessGroupPK();
            }
            return id;
        }
    
        public void setId(UserProfileAccessGroupPK id) {
            this.id = id;
        }
    
        public Date getExpirationDate() {
            return expirationDate;
        }
    
        public void setExpirationDate(Date expirationDate) {
            this.expirationDate = expirationDate;
        }
    
        public UserProfile getAuthorizedBy() {
            return authorizedBy;
        }
    
        public void setAuthorizedBy(UserProfile authorizedBy) {
            this.authorizedBy = authorizedBy;
        }
    
        @Embeddable
        public static class UserProfileAccessGroupPK implements Serializable {
    
            private static final long serialVersionUID = 1L;
    
            @ManyToOne
            @JoinColumn(name = "accessGroupId")
            private AccessGroup accessGroup;
    
            @ManyToOne
            @JoinColumn(name = "userProfileId")
            private UserProfile userProfile;
    
            public UserProfileAccessGroupPK() {
            }
    
            public UserProfileAccessGroupPK(AccessGroup accessGroup, UserProfile userProfile) {
                this.accessGroup = accessGroup;
                this.userProfile = userProfile;
            }
    
            public AccessGroup getAccessGroup() {
                return accessGroup;
            }
    
            public void setAccessGroup(AccessGroup accessGroup) {
                this.accessGroup = accessGroup;
            }
    
            public UserProfile getUserProfile() {
                return userProfile;
            }
    
            public void setUserProfile(UserProfile userProfile) {
                this.userProfile = userProfile;
            }
    
            @Override
            public int hashCode() {
                final int prime = 31;
                int result = 1;
                result = prime * result + ((accessGroup == null) ? 0 : accessGroup.hashCode());
                result = prime * result + ((userProfile == null) ? 0 : userProfile.hashCode());
                return result;
            }
    
            @Override
            public boolean equals(Object obj) {
                if (this == obj)
                    return true;
                if (obj == null)
                    return false;
                if (getClass() != obj.getClass())
                    return false;
                UserProfileAccessGroupPK other = (UserProfileAccessGroupPK) obj;
                if (accessGroup == null) {
                    if (other.accessGroup != null)
                        return false;
                } else if (!accessGroup.equals(other.accessGroup))
                    return false;
                if (userProfile == null) {
                    if (other.userProfile != null)
                        return false;
                } else if (!userProfile.equals(other.userProfile))
                    return false;
                return true;
            }
        }
    }
    

    Affects: 1.10.1 (Hopper SR1)

    Attachments:

    Issue Links:

    • DATAJPA-913 Inconsistent behavior with projections when using @NamedQuery vs @Query ("is duplicated by")

    • DATAJPA-984 JPA projection query returning single non-standard JPA type results in "No aliases found in result tuple" error

    • DATACMNS-862 ReturnedInterface should not consider super interfaces of domain type projecting

    • DATAREST-841 Add support for query methods returning a projection

    Backported to: 1.10.2 (Hopper SR2)

    0 votes, 13 watchers

    type: bug in: core 
    opened by spring-projects-issues 55
  • Context enabled JPA 2.1 @EntityGraph  [DATAJPA-749]

    Context enabled JPA 2.1 @EntityGraph [DATAJPA-749]

    Bartłomiej Mocior opened DATAJPA-749 and commented

    Currently It's impossible to enable EntityGraph configuration outside of spring data jpa repository. The only possibility is to use @EntityGraph annotation over query method.

    for example

    @EntityGraph("summary")
    Optional<Customer> findByEmailAddress(EmailAddress emailAddress);
    

    Now, it's impossible to reuse this method in different contexts where different entity graph aka fetch profile is required.

    Example I have entity Customer with 2 relations: Invoices and Addresses (OneToMany)

    • In context 1, let's say 'Displaying Customer data with invoices list' I would like to fetch Customer + invoices only.
    • In context 2, let's say 'Displaying Customer data with Addresses' I would like to fetch Customer + addresses only.

    Now, with spring data jpa, I have to create another (second) method and annotate it with another "context" @EntityGraph. What is more, my method's name should generate the same JQL Query, but must have different signature (because it's in the same repository), so I will end up with @Query annotation and code duplication.

    The current implementation don't allow to set QueryHints directly on Query - it's possible to annotate method with @QueryHint but it won't solve the problem because it's AFAIK static, and doesn't use SpEL.

    Jpa21Utils with tryGetFetchGraphHints get's the query hints from annotation only, maybe it would be good idea if it could additionally take from other source ? Maybe ThreadLocale or any context object ? Maybe, It would be consistent with spring data API if we could provide EntityGraphContext object to have full controll of execution ?

    Proposed solution I "EntityGraphContext"- repository example

    interface SomeRepository ... 
    Optional<Customer> findByEmailAddress(EmailAddress emailAddress, EntityGraphContext graphCtx);
    

    Client code:

    EntityGraphContext graphCtx = EntityGraphContext.enable("summary").withType(EntityGraphType.FETCH);
    Optonal<Customer> customer = someRepository.findByEmailAddress(address, graphCtx);
    

    Proposed solution II "EntityGraphThreadLocalContext"- repository example

    interface SomeRepository ... 
    Optional<Customer> findByEmailAddress(EmailAddress emailAddress);
    

    Client code:

    EntityGraphThreadLocalContext.enable("summary").withType(EntityGraphType.FETCH);
    Optonal<Customer> customer = someRepository.findByEmailAddress(address);
    

    Affects: 1.9 M1 (Gosling)

    13 votes, 17 watchers

    status: declined in: core type: enhancement has: votes-jira 
    opened by spring-projects-issues 44
  • Cannot create a repository for entity with @IdClass [DATAJPA-50]

    Cannot create a repository for entity with @IdClass [DATAJPA-50]

    GWA opened DATAJPA-50 and commented

    When I want to create a JpaRepository with an Entity like this:

    @Entity
    @IdClass(MyEntityPK)
    public class MyEntity{
      @Id private String parent;
      @Id private int order;
      …
    }
    

    MyEntityPK is a simple bean with String parent; int order; . Then i get the following error :

    java.lang.IllegalStateException: No supertype found
    	at org.hibernate.ejb.metamodel.AbstractIdentifiableType.requireSupertype(AbstractIdentifiableType.java:74)
    	at org.hibernate.ejb.metamodel.AbstractIdentifiableType.getIdType(AbstractIdentifiableType.java:162)
    	at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:65)
    	at org.springframework.data.jpa.repository.utils.JpaClassUtils.getMetadata(JpaClassUtils.java:103)
    

    Affects: 1.0 M2

    Attachments:

    Referenced from: commits https://github.com/spring-projects/spring-data-jpa/commit/3962f1ab31b7d9ab2ad650a720b10a0617419d53

    13 votes, 18 watchers

    in: core type: enhancement has: votes-jira 
    opened by spring-projects-issues 43
  • Support projections on query methods that take a dynamic query type (Specification or Querydsl Predicate) [DATAJPA-1033]

    Support projections on query methods that take a dynamic query type (Specification or Querydsl Predicate) [DATAJPA-1033]

    Sebastian Staudt opened DATAJPA-1033 and commented

    Currently there seems no (at least no obvious) way to mix projections and specifications.

    class ExampleRepository extends JpaRepository<Example, Integer>, JpaSpecificationExecutor<Example> {
    
        // Overriden from JpaRepository, just to show the whole picture
        // Works without problems
        @Override
        List<Example> findAll();
    
        // A bit odd, due to the "By", but works - see DATAJPA-680
        List<ExampleProjection> findAllProjectedBy();
    
        // Overriden from JpaRepository, just to show the whole picture
        // Works without problems
        @Override
        List<Example> findAll(Specification<Example> spec);
    
        // This would be great, but doesn't work.
        List<ExampleProjection> findAllProjectedBy(Specification<Example> spec);
    
    }
    

    A query method like the last above causes a java.util.NoSuchElementException inside org.springframework.data.jpa.repository.query.CriteriaQueryParameterBinder#bind during query. (Which may be another problem on its own.)


    Affects: 2.0 M1 (Kay), 1.11 RC1 (Ingalls), 1.10.6 (Hopper SR6)

    Issue Links:

    • DATAJPA-393 Add support for QueryDSL projections in JPA repositories

    Referenced from: pull request https://github.com/spring-projects/spring-data-jpa/pull/430

    107 votes, 96 watchers

    status: superseded in: core type: enhancement has: votes-jira 
    opened by spring-projects-issues 40
  • Complex select clauses in manually declared query using constructor expressions fail [DATAJPA-938]

    Complex select clauses in manually declared query using constructor expressions fail [DATAJPA-938]

    Andriy Senko opened DATAJPA-938 and commented

    If repository contains HQL query with "SELECT new" statement Spring Data Jpa fails with exception. I got this behaviour after I updated version from 1.9.1.RELEASE to 1.10.2.RELEASE. I reproduced this behaviour on 1.10.1.RELEASE version.

    Example of repository method:

    @Query("select new com.Dto( o.field1, o.field2, o.field3) from Order o")
    List<Dto> findOrders();
    

    Exception:

    java.lang.IllegalArgumentException: org.hibernate.QueryException: ResultTransformer is not allowed for 'select new' queries.
    	at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1679) ~[hibernate-entitymanager-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) ~[hibernate-entitymanager-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:445) ~[hibernate-entitymanager-5.0.2.Final.jar:5.0.2.Final]
    	at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:114) ~[spring-data-jpa-1.10.1.RELEASE.jar:na]
    	at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:78) ~[spring-data-jpa-1.10.1.RELEASE.jar:na]
    	at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:102) ~[spring-data-jpa-1.10.1.RELEASE.jar:na]
    	at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:92) ~[spring-data-jpa-1.10.1.RELEASE.jar:na]
    	at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482) ~[spring-data-commons-1.12.2.RELEASE.jar:na]
    	at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460) ~[spring-data-commons-1.12.2.RELEASE.jar:na]
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.12.2.RELEASE.jar:na]
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.10.1.RELEASE.jar:na]
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at com.sun.proxy.$Proxy498.findPromoDealOfferings(Unknown Source) ~[na:na]
    	at com.frontier.service.deal.DealOfferingService.getForPromoDeal(DealOfferingService.java:707) ~[deal-service-1.0.37-SNAPSHOT.jar:na]
    	at com.frontier.service.deal.DealOfferingService.find(DealOfferingService.java:644) ~[deal-service-1.0.37-SNAPSHOT.jar:na]
    	at com.frontier.service.deal.DealOfferingService$$FastClassBySpringCGLIB$$68ebdfce.invoke(<generated>) ~[deal-service-1.0.37-SNAPSHOT.jar:na]
    	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:718) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:654) ~[spring-aop-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at com.frontier.service.deal.DealOfferingService$$EnhancerBySpringCGLIB$$b99e020e.find(<generated>) ~[deal-service-1.0.37-SNAPSHOT.jar:na]
    	at com.frontier.controller.deal.DealOfferingController.find(DealOfferingController.java:27) ~[deal-service-1.0.37-SNAPSHOT.jar:na]
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
    	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
    	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) ~[spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) ~[spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) ~[spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) ~[spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:620) [servlet-api.jar:na]
    	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) [servlet-api.jar:na]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) [catalina.jar:7.0.54]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.54]
    	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) [spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.54]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.54]
    	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat7-websocket.jar:7.0.54]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.54]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.54]
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) [catalina.jar:7.0.54]
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) [catalina.jar:7.0.54]
    	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) [catalina.jar:7.0.54]
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) [catalina.jar:7.0.54]
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [catalina.jar:7.0.54]
    	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) [catalina.jar:7.0.54]
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) [catalina.jar:7.0.54]
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) [catalina.jar:7.0.54]
    	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) [tomcat-coyote.jar:7.0.54]
    	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) [tomcat-coyote.jar:7.0.54]
    	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) [tomcat-coyote.jar:7.0.54]
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
    	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-coyote.jar:7.0.54]
    	at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
    Caused by: org.hibernate.QueryException: ResultTransformer is not allowed for 'select new' queries.
    	at org.hibernate.loader.hql.QueryLoader.checkQuery(QueryLoader.java:506) ~[hibernate-core-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:500) ~[hibernate-core-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) ~[hibernate-core-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220) ~[hibernate-core-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1268) ~[hibernate-core-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) ~[hibernate-core-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:567) ~[hibernate-entitymanager-5.0.2.Final.jar:5.0.2.Final]
    	at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:436) ~[hibernate-entitymanager-5.0.2.Final.jar:5.0.2.Final]
    	... 75 common frames omitted
    

    Affects: 1.10.1 (Hopper SR1), 1.10.2 (Hopper SR2)

    Attachments:

    Referenced from: commits https://github.com/spring-projects/spring-data-jpa/commit/7372ffdf2d770ee5d213fbe948f8e5fcb4d0c333, https://github.com/spring-projects/spring-data-jpa/commit/bcc917867e6e78007298225768875f08449bd47e, https://github.com/spring-projects/spring-data-jpa/commit/937c650276ef33af696576a0f31c88b2612d7330, https://github.com/spring-projects/spring-data-jpa/commit/2068036d0cebcc6b76a5b77c5e16aa47b7aab791, https://github.com/spring-projects/spring-data-jpa/commit/21991ce5c6f08e26ccd1d33812aa87c3a3608549, https://github.com/spring-projects/spring-data-jpa/commit/171477ccc0e756fd78845d4cc804c6678b42df41

    Backported to: 1.10.3 (Hopper SR3)

    0 votes, 7 watchers

    type: bug in: core 
    opened by spring-projects-issues 39
  • Improve handling of null query method parameter values [DATAJPA-209]

    Improve handling of null query method parameter values [DATAJPA-209]

    Matthew T. Adams opened DATAJPA-209 and commented

    In 1.1.0.RC1 and prior, query methods expect non-null values. If a null value is passed in to a query method, the JPQL generated includes an "= NULL" condition, which is always false.

    SD JPA supports query method keyword IsNull, which allows for testing explicitly whether a value is null. This is ok, but fails to meet our requirement of using null parameter values to indicate that that parameter should be ignored and not included in the query.

    Here's an example. Suppose I have a Foo that references a Bar and a Goo, and I want to create a query that finds me any Foo instances that reference a given Bar and/or Goo. The query method would look like this:

    public interface FooRepository extends JpaRepository<Foo> {
    
      List<Foo> findByBarAndGoo(Bar bar, Goo goo);
    }
    

    If this method is called with a non-null values for both parameters, everything works fine. However, if you pass null for either parameter, no Foo instances are found because = NULL is always false. One alternative is for the author to write custom, boilerplate method implementations that handle null instances as desired. Another alternative is to write a collection of methods representing all of the permutations of the nullable parameters, which doesn't really scale well past two or three parameters:

    public interface FooRepository extends JpaRepository<Foo> {
    
      List<Foo> findByBarAndGoo(Bar bar, Goo goo);
      List<Foo> findByBar(Bar bar);
      List<Foo> findByGoo(Goo goo);
    }
    

    This issue represents a request to improve this situation.

    Consider a new enum & annotation:

    public enum NullBehavior {
    	EQUALS, IS, IGNORED
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
    public @interface NullMeans {
    	NullBehavior value() default NullBehavior.EQUALS;
    }
    

    With this annotation, SD JPA would let the author decide how to behave when null parameters are encountered. In the absence of the annotation, the current default behavior (= NULL) would apply. If the author uses @NullMeans(IS), then SD JPA will produce an IS NULL clause. If they use @NullMeans(IGNORED), then SD JPA does not include a clause for the given parameter.

    Now, reconsider the Foo example. I now have a flexible way of specifying the queries I want.

    public interface FooRepository extends JpaRepository<Foo> {
    
      List<Foo> findByBarAndGoo(@NullMeans(IGNORED) Bar bar, @NullMeans(IGNORED) Goo goo);
    }
    

    This also scales well:

    public interface BlazRepository extends JpaRepository<Blaz> {
    
      @NullMeans(IGNORED) // applies to all parameters unless overriden by @NullMeans on parameter(s)
      List<Blaz> findByFooAndGooAndHooAndKooAndLoo(Foo foo, Goo goo, Hoo hoo, Koo koo, @NullMeans(IS) Loo loo);
    }
    

    I've also allowed @NullMeans to be placed on the interface as well, which would provide a default for all parameters on all query methods defined in the interface. I would imagine that many folks would use @NullMeans(IGNORED) at the interface level since it's so practical


    Affects: 1.1 RC1

    Issue Links:

    • DATACMNS-1319 Suggestion: change interpretation of Optionals as parameters in Spring Data JPA repositories interfaces ("is duplicated by")

    • DATAJPA-121 Query parameter is null,it still use equals(=) to compare

    • DATACMNS-490 Add support for optional query method parameters

    77 votes, 72 watchers

    status: declined type: enhancement has: votes-jira 
    opened by spring-projects-issues 38
  • Nested Id classes fail to populate in JpaMetamodelEntityInformation [DATAJPA-413]

    Nested Id classes fail to populate in JpaMetamodelEntityInformation [DATAJPA-413]

    Brian Chase opened DATAJPA-413 and commented

    I have 2 JPA entities that have compound keys, and so both are using the @IdClass object to store the compound primary key.

    The first entity and id class uses two integers as the compound key.

     
    @Entity
    @IdClass(ItemId.class)
    public class Item {
    	
    	@Id
    	@Column(columnDefinition = "INT")
    	private Integer id;
    
    	@Id
    	@Column(name = "sales_device_id", columnDefinition = "INT")
    	private Integer salesDeviceId;
    
    	....
    }
    
    
    public class ItemId implements Serializable {
    	
    	public Integer id;
    	
    	public Integer salesDeviceId;
    
    	....
    }
    

    The second entity and id class uses three integers as the compound key, however I am using entities as the @Id values. Two of the primary key columns are part of the Item entity, and the third column belongs to the Site entity.

     
    @Entity
    @IdClass(ItemSiteId.class)
    public class ItemSite {
    	
    	@Id
    	@ManyToOne
    	private Item item;
    	
    	@Id
    	@ManyToOne
    	private Site site;
    
    	....
    }
    

    For this case the Id class for ItemSite must use the Id class from Item as described in the OpenJPA documentation in example 5.6 http://openjpa.apache.org/builds/2.2.2/apache-openjpa/docs/ref_guide_pc_oid.htmll

     
    public class ItemSiteId implements Serializable {
    	
    	public ItemId item;
    	
    	public Integer site;
    
    	....
    }
    

    Using these nested Id classes, spring data throws an exception of type conversion failure from the JpaMetamodelEntityInformation class. After downloading version 1.4.1 source, I applied a rewrite of the IdentifierDerivingDirectFieldAccessFallbackBeanWrapper method setPropertyValue (around line 323 in JpaMetamodelEntityInformation) and it resolves the exception.

    Here is my change:

     
    @Override
    public void setPropertyValue(String propertyName, Object value) {
    
    	if (isIdentifierDerivationNecessary(value)) {
    
    		// Derive the identifer from the nested entity that is part of the composite key.
    		@SuppressWarnings({ "rawtypes", "unchecked" })
    		JpaMetamodelEntityInformation nestedEntityInformation = new JpaMetamodelEntityInformation(value.getClass(),
    				this.metamodel);
    		
    		super.setPropertyValue(propertyName, nestedEntityInformation.getId(value));
    		return;
    	}
    
    	super.setPropertyValue(propertyName, value);
    }
    

    Affects: 1.4.1

    Reference URL: http://openjpa.apache.org/builds/2.2.2/apache-openjpa/docs/ref_guide_pc_oid.html

    Attachments:

    Referenced from: pull request https://github.com/spring-projects/spring-data-jpa/pull/133

    Backported to: 1.10.3 (Hopper SR3), 1.9.5 (Gosling SR5)

    8 votes, 11 watchers

    type: bug in: core 
    opened by spring-projects-issues 30
  • NativeQuery with Pagination

    NativeQuery with Pagination

    Hello, I am facing issue similiar with https://github.com/spring-projects/spring-data-jpa/issues/1282.

    I am trying to run this native query with spring-data on version 2.5.0

    @Query(value = "SELECT dense_rank() OVER (ORDER BY rank DESC)," + "t.id, " + "FROM table t WHERE t.x > 0 ", nativeQuery = true) Page<Object[]> getT(Pageable pageable);

    But I am getting SQLGrammarException because the spring-data engine will translate this query into

    SELECT dense_rank() OVER (ORDER BY rank DESC),t.id FROM table t WHERE t.x > 0 , t.y desc limit 20

    Where the problem is pretty obvious. There is ORDER BY clause missing, probably because of presence of ORDER BY clause in OVER subquery. Is this a known bug? And is it possible to bypass this somehow? I need to use whole pageable object with native query with this dense_rank() calling.

    type: bug in: query-parser 
    opened by Johnczek 29
  • Add option so that CrudRepository.findOne throws an unchecked exception if entity is not found [DATAJPA-118]

    Add option so that CrudRepository.findOne throws an unchecked exception if entity is not found [DATAJPA-118]

    Adrian opened DATAJPA-118 and commented

    For a clean design it would be great if I could set an option (maybe on the jpa:repository tag) that will throw a javax.persistence.EntityNotFoundException (or some other unchecked exception) instead of returning null if CrudRepository.findOne does not find the entity.


    Issue Links:

    • DATAJPA-301 Add CrudRepository#findExpected(ID) ("is duplicated by")

    14 votes, 25 watchers

    status: declined type: enhancement has: votes-jira 
    opened by spring-projects-issues 28
  • Issue with spring-data

    Issue with spring-data "startingWith" and hibernate 5.6.7: Parameter value [\] did not match expected type [java.lang.String (n/a)]" with findAllByXXXStartingWith

    Hello,

    I am trying to fetch some entity using a “find all by property starting with” query which amount to a CriteriaQuery using javax.persistence.criteria.CriteriaBuilder.like(Expression, String, char)

    When migrating to hibernate-entitymanager 5.6.7.Final I do have this error:

    java.lang.IllegalArgumentException: Parameter value [\] did not match expected type [java.lang.String (n/a)]
    	at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:27) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.query.internal.QueryParameterBindingImpl.validate(QueryParameterBindingImpl.java:90) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.query.internal.QueryParameterBindingImpl.setBindValue(QueryParameterBindingImpl.java:55) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:501) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:122) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.query.criteria.internal.compile.CriteriaCompiler$1$1.bind(CriteriaCompiler.java:141) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.query.criteria.internal.CriteriaQueryImpl$1.buildCompiledQuery(CriteriaQueryImpl.java:364) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.query.criteria.internal.compile.CriteriaCompiler.compile(CriteriaCompiler.java:171) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:774) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    	at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:114) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    

    It seems to happens when invoking twice the same method (in the attached demo_spring-data-2.6.3_hibernate_5.6.7..zip, findByLastNameStartingWith):

    In the first invocation, we can see the validate (org.hibernate.query.spi.QueryParameterBindingValidator.validate(Type, Object, TemporalType)) takes the following arguments set:

    • null, '', null
    • org.hibernate.type.StringType, ‘Bauer%’, null

    In the second case:

    • org.hibernate.type.StringType, '', null => FAILS (StringType expect a String, but got a Character)

    The demo (was generated using Spring Initializer and this doc: https://www.baeldung.com/spring-data-jpa-query: demo_spring-data-2.6.3_hibernate_5.6.7..zip. It can be imported as Maven project in Eclipse and IntelliJ.

    Note: I did try using CriteriaQuery as shown below and got no error and that's why I created issue here instead of hibernate, since I'm not sure where the problem might be (I would say that it is in Hibernate but given the example below works, there might be more to it):

        private static void demonstrateWithCriteria(EntityManager em) {
            CriteriaBuilder b = em.getCriteriaBuilder();
            CriteriaQuery<Customer> q = b.createQuery(Customer.class);
            q.where(b.like(q.from(Customer.class).<String> get("lastName"), b.literal("Bauer%"), '\\'));
    
            log.info("Test1 -- Customer found with criteria");
            em.createQuery(q).getResultList().forEach(bauer -> {
                log.info(bauer.toString());
            });
    
            log.info("Test2 -- Customer found with criteria");
            em.createQuery(q).getResultList().forEach(bauer -> {
                log.info(bauer.toString());
            });
        }
    

    Versions information:

    • hibernate-core: 5.6.7.Final (tested also with 5.6.6.Final)
    • spring-data 2.6.2 / 2.6.3
    • java 1.8.0_322 (temurin / adoptium)
    • windows / linux (wsl)
    for: external-project status: invalid 
    opened by glhez 26
  • Provide support for ParameterMode.REF_CURSOR - Hibernate [DATAJPA-1145]

    Provide support for ParameterMode.REF_CURSOR - Hibernate [DATAJPA-1145]

    Vishnudev K opened DATAJPA-1145 and commented

    I was trying to execute a oracle procedure with spring-data-jpa and hibernate

    
    PROCEDURE MY_PROC (
        P_ID IN NUMBER,
        P_PERIOD IN VARCHAR2,
        P_LIMIT IN NUMBER,
        P_CURSOR OUT T_CURSOR);
    
    

    MyEntity.java

    @NamedStoredProcedureQuery(
            name = "myProc",
            procedureName = "MY_PROC",
            resultClasses = ResultEntity.class,
            parameters = {
                @StoredProcedureParameter(mode = ParameterMode.IN, type = Long.class),
                @StoredProcedureParameter(mode = ParameterMode.IN, type = String.class),
                @StoredProcedureParameter(mode = ParameterMode.IN, type = Long.class),
                @StoredProcedureParameter(mode = ParameterMode.REF_CURSOR, type = void.class)
    
    
    

    MyRepository.java

    
    @Procedure(name = "myProc", procedureName = "MY_PROC")
        List<ResultEntity> execMyProc(Long userId,String period,Long idClientLimit);
    
    
    StoredProcedureQuery query = entityManager.createNamedStoredProcedureQuery("extractWebUser");
    query.setParameter(1, userId);
    query.setParameter(2, period);
    query.setParameter(3, idClientLimit);
    query.execute();
    List resultList = query.getResultList();
    
    

    But on spring-data we need to use getOutputParameterValue Method instead of getResultList

    Object outputParameterValue = query.getOutputParameterValue(4);
    

    Then I discovered that the hibernate does not support REF_CURSOR

    org.hibernate.procedure.internal.AbstractParameterRegistrationImpl.java

    
    ...
    ...
    public T extract(CallableStatement statement) {
    ...
    else if ( mode == ParameterMode.REF_CURSOR ) {
                throw new ParameterMisuseException( "REF_CURSOR parameters should be accessed via results" );
            }
    ...
    

    As per the ticket https://jira.spring.io/browse/DATAJPA-652 its working fine on eclipse link, but broken in hibernate for quite sometime. (I have taken the data/details from the original ticket)


    Reference URL: https://github.com/spring-projects/spring-data-jpa/pull/207

    Attachments:

    type: bug status: declined in: core 
    opened by spring-projects-issues 23
  • Native Image Fails w/ Multiple DataSources

    Native Image Fails w/ Multiple DataSources

        It looks to me like the references configured on `@EnableJpaRepositories` aren't being applied correctly. I suspect that this is a Spring Data JPA bug but it could also be a Spring Framework problem. @matthenry87 please open a Spring Data JPA issue and we can take things from there.
    

    Originally posted by @wilkinsona in https://github.com/spring-projects/spring-boot/issues/33656#issuecomment-1369838626

    Trying to do all of the groundwork for our teams to start using native images. We use multiple data sources in over half of our applications.

    Example project: https://github.com/matthenry87/native-image-multiple-datasource-testing

    Spring Boot 3.0.1

    GraalVM 22.3.0 Java 17 CE Java version info: '17.0.5+8-jvmci-22.3-b08' C compiler: gcc (linux, x86_64, 9.4.0) Garbage collector: Serial GC

    Using GraalVM native-image directly via mvn native:compile -Pnative -DskipTests

    Error:

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::                (v3.0.1)
    
    2022-12-29T19:13:40.616-07:00  INFO 30729 --- [           main] o.m.nativetesting.api.ApiApplication     : Starting AOT-processed ApiApplication using Java 17.0.5 with PID 30729 (/mnt/c/workspace/native-image-multimodule-testing/api/target/api started by matt in /mnt/c/workspace/native-image-multimodule-testing)
    2022-12-29T19:13:40.617-07:00  INFO 30729 --- [           main] o.m.nativetesting.api.ApiApplication     : No active profile set, falling back to 1 default profile: "default"
    2022-12-29T19:13:40.631-07:00  WARN 30729 --- [           main] o.s.c.support.GenericApplicationContext  : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'db1Service': Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'fooEntityRepository': Unexpected exception during bean creation
    2022-12-29T19:13:40.633-07:00 ERROR 30729 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :
    
    ***************************
    APPLICATION FAILED TO START
    ***************************
    
    Description:
    
    Parameter 0 of constructor in org.matthenry87.nativetesting.persistence.db1.Db1Service required a single bean, but 2 were found:
            - db1EntityManagerFactory: defined by method 'db1EntityManagerFactory' in null
            - db2EntityManagerFactory: defined by method 'db2EntityManagerFactory' in null
    
    
    Action:
    
    Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
    

    Funny thing, is that the Db1Service injects a single repository class, not an EntityManager.

    status: waiting-for-triage 
    opened by matthenry87 2
  • Refactored AssertJ assertions into more readable ones

    Refactored AssertJ assertions into more readable ones

    Optimized AssertJ assertions into more readable ones (and giving better error messages) also replaced junit assumptions with AssertJ ones (for consistency).

    status: waiting-for-triage 
    opened by krzyk 0
  • Build fails in ParentRepositoryIntegrationTests and RoleRepositoryIntegrationTests

    Build fails in ParentRepositoryIntegrationTests and RoleRepositoryIntegrationTests

    I did a fresh checkout of the main branch and tried ./mvnw clean install and it failed with:

    [ERROR] Errors:
    [ERROR]   ParentRepositoryIntegrationTests.setUp:58 » BeanCreation Error creating bean w...
    [ERROR]   ParentRepositoryIntegrationTests.setUp:58 » BeanCreation Error creating bean w...
    [ERROR]   RoleRepositoryIntegrationTests.createsRole:51 » BeanCreation Error creating be...
    [ERROR]   RoleRepositoryIntegrationTests.shouldUseExplicitlyConfiguredEntityNameInDerivedCountQueries:91 » BeanCreation
    [ERROR]   RoleRepositoryIntegrationTests.shouldUseExplicitlyConfiguredEntityNameInOrmXmlInCountQueries:73 » BeanCreation
    [ERROR]   RoleRepositoryIntegrationTests.shouldUseExplicitlyConfiguredEntityNameInOrmXmlInExistsQueries:82 » BeanCreation
    [ERROR]   RoleRepositoryIntegrationTests.updatesRole:59 » BeanCreation Error creating be...
    

    One of stacktraces:

    [ERROR] org.springframework.data.jpa.repository.ParentRepositoryIntegrationTests.testWithJoin  Time elapsed: 0.003 s  <<< ERROR!
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.auditing.AuditingHandler#0': Cannot create inner bean '(inner bean)#461c9e86' of type [org.springframework.data.repository.config.PersistentEntitiesFactoryBean] while setting constructor argument
            at org.springframework.data.jpa.repository.ParentRepositoryIntegrationTests.setUp(ParentRepositoryIntegrationTests.java:58)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#461c9e86': Cannot resolve reference to bean 'jpaMappingContext' while setting constructor argument
            at org.springframework.data.jpa.repository.ParentRepositoryIntegrationTests.setUp(ParentRepositoryIntegrationTests.java:58)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': org.springframework.context.support.GenericApplicationContext@7a66b886 has been closed already
            at org.springframework.data.jpa.repository.ParentRepositoryIntegrationTests.setUp(ParentRepositoryIntegrationTests.java:58)
    Caused by: java.lang.IllegalStateException: org.springframework.context.support.GenericApplicationContext@7a66b886 has been closed already
            at org.springframework.data.jpa.repository.ParentRepositoryIntegrationTests.setUp(ParentRepositoryIntegrationTests.java:58)
    

    I couldn't find any information in CONTRIBUTING or in README that I should setup my environment in specific way to allow those tests to pass.

    type: task 
    opened by krzyk 5
  • Incorrect results for pageable EntityGraph with spring data and spring-boot v3.0.1

    Incorrect results for pageable EntityGraph with spring data and spring-boot v3.0.1

    Bug description

    I created test application with custom repository with the help of spring boot v3.0.1 and org.springframework.boot:spring-boot-starter-data-jpa. With findAll function in repository I want to load related entities with entity graph. When I call this method I get single SQL request to DB with offset and fetch at the end. It lead to getting wrong result from db because with entity graph I get a cartesian product fom DB as a result. For example I can get different totalElements result for same data in DB.

    @Repository
    interface ClientRepository : JpaRepository<ClientEntity, Long> {
    
        @EntityGraph(attributePaths = ["accounts", "deposits"])
        override fun findAll(pageable: Pageable): Page<ClientEntity>
    }
    

    Client entity class

    @Entity
    @Table(name = "CLIENT")
    class ClientEntity(
    
        @Id
        @Column(name = "ID")
        var id: Long? = null,
    
        @Embedded
        var clientName: ClientName? = null,
    
        @Embedded
        var clientAddress: Address? = null,
    
        @OneToMany(mappedBy = "client")
        var accounts: Set<AccountEntity> = mutableSetOf(),
    
        @OneToMany(mappedBy = "client")
        var deposits: Set<DepositEntity> = mutableSetOf()
    )
    

    Expected behavior

    Got that result with spring boot 2.7.7 r.r.b.c.g.n.v.BankDemoNProblemController : getClientList(page: 0, size: 3, extracting_strategy: EXTRACTING_STRATEGY_ENTITY_GRAPH) WARN 94791 --- [atcher-worker-1] o.h.h.internal.ast.QueryTranslatorImpl : HHH000104: firstResult/maxResults specified with collection fetch; applying in memory! Hibernate: select cliententi0_.id as id1_2_0_, deposits1_.id as id1_3_1_, accounts2_.id as id1_0_2_, cliententi0_.address_city as address_2_2_0_, cliententi0_.address_flat as address_3_2_0_, cliententi0_.address_house as address_4_2_0_, cliententi0_.address_street as address_5_2_0_, cliententi0_.client_first_name as client_f6_2_0_, cliententi0_.client_last_name as client_l7_2_0_, cliententi0_.client_middle_name as client_m8_2_0_, deposits1_.amount as amount2_3_1_, deposits1_.client_id as client_i4_3_1_, deposits1_.rate as rate3_3_1_, deposits1_.client_id as client_i4_3_0__, deposits1_.id as id1_3_0__, accounts2_.amount as amount2_0_2_, accounts2_.client_id as client_i4_0_2_, accounts2_.number as number3_0_2_, accounts2_.client_id as client_i4_0_1__, accounts2_.id as id1_0_1__ from client cliententi0_ left outer join deposit deposits1_ on cliententi0_.id=deposits1_.client_id left outer join account accounts2_ on cliententi0_.id=accounts2_.client_id Hibernate: select count(cliententi0_.id) as col_0_0_ from client cliententi0_

    You can see that SQLrequest presented above without offset ? rows fetch first ? rows only As a result I get right total elements and content size for findAll(pageable: Pageable) with different pageable parameters. test4 test3 You can see above the same total count for page 1 and 2 (for three clients in a database). I got WARN 94791 --- [atcher-worker-1] o.h.h.internal.ast.QueryTranslatorImpl : HHH000104: firstResult/maxResults specified with collection fetch; applying in memory! it's not very efficient but it works

    Actual behavior

    Got that result with spring boot 3.0.1 r.r.b.c.g.n.v.BankDemoNProblemController : getClientList(page: 0, size: 3, extracting_strategy: EXTRACTING_STRATEGY_ENTITY_GRAPH) Hibernate: select c1_0.id,a1_0.client_id,a1_0.id,a1_0.amount,a1_0.number,c1_0.address_city,c1_0.address_flat,c1_0.address_house,c1_0.address_street,c1_0.client_first_name,c1_0.client_last_name,c1_0.client_middle_name,d1_0.client_id,d1_0.id,d1_0.amount,d1_0.rate from client c1_0 left join account a1_0 on c1_0.id=a1_0.client_id left join deposit d1_0 on c1_0.id=d1_0.client_id offset ? rows fetch first ? rows only

    You can see that SQLrequest presented above with offset ? rows fetch first ? rows only As a result I get wrong total elements for findAll(pageable: Pageable) with different pageable parameters. test2 test1 You can see different total count and wrong content size for page 1 and page 2 (for three clients in a database).

    I use

    Kotlin - 1.7.21 Spring-boot - 2.7.7 and 3.0.1 Spring dependency management - 1.1.0

    for: external-project status: waiting-for-feedback status: waiting-for-triage 
    opened by arvgord 1
  • Perfect match search for char type with Like in JPA does not work

    Perfect match search for char type with Like in JPA does not work

    I am unable to do a Perfect Match search for a char type with Like in JPA.

    I have searched with Perfect match Like for a column of type char against SQL Server2022, but when I execute the SQL directly. But when I bind the parameter with JPA, it doesn't hit the search.

    table

    • talbe name : test

    • table layout

    |type|name|value| |:--|:--|:--| |varchar(25)|key|0001| |varchar(2)|chardata|2| |varchar(2)|varchardata|2|

    Entity

    @Data
    public abstract class BaseDbEntity<T> implements Persistable<T> {
    
        private boolean newFlag = false;
    
        @Override
        public boolean isNew() {
            return newFlag;
        }
    }
    
    @Entity
    @Table(name = "test")
    @Data
    @EqualsAndHashCode(callSuper=true)
    @ToString(callSuper=true)
    public class TestEntity extends BaseDbEntity<String> {
    
        @Id
        @Column(name = "key")
        private String key;
    
        @Column(name = "chardata")
        private String chardata;
    
        @Column(name = "varchardata")
        private String varchardata;
    
        @Override
        public String getId() {
            return this.key;
        }
    }
    

    Repository

    @Repository
    public interface TestRepository extends JpaRepository<TestEntity, String> {
    
        @Query(nativeQuery = true)
        List<TestEntity> findCustomByForm1(@Param("chardata") String chardata);
        List<TestEntity> findCustomByForm2(@Param("varchardata") String chardata);
        List<TestEntity> findCustomByForm3();
    }
    
    TestEntity.findCustomByForm1= SELECT * FROM test t1 WHERE t1.chardata LIKE :chardata
    TestEntity.findCustomByForm2= SELECT * FROM test t1 WHERE t1.varchardata LIKE :varchardata
    TestEntity.findCustomByForm3= SELECT * FROM test t1 WHERE t1.chardata '2'
    

    SQL Result

    • like char(binding parameter)=> result: 0 record
    Hibernate: SELECT * FROM test t1 WHERE t1.chardata LIKE ?
    binding parameter [1] as [VARCHAR] - [2]
    
    • like varchar(binding parameter) => result: 1 record
    Hibernate: SELECT * FROM test t1 WHERE t1.varchardata LIKE ?
    binding parameter [1] as [VARCHAR] - [2]
    
    • like char => result: 1 record
    Hibernate: SELECT * FROM test t1 WHERE t1.chardata LIKE '2'
    
    status: waiting-for-feedback status: waiting-for-triage 
    opened by 11ohina017 1
  • "Could not safely identify store assignment" messages with multiple Spring Data modules (JPA / MongoDB)

    Spring Data version: 2.6.0

    I am getting the following errors on application start:

    2022-12-22 11:54:44.370  INFO 10552 --- [    Test worker] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface org.example.mongodb.MyMongoDbRepository. If you want this repository to be a JPA repository, consider annotating your entities with one of these annotations: javax.persistence.Entity, javax.persistence.MappedSuperclass (preferred), or consider extending one of the following types with your repository: org.springframework.data.jpa.repository.JpaRepository.
    ...
    2022-12-22 11:54:44.784  INFO 10552 --- [    Test worker] .RepositoryConfigurationExtensionSupport : Spring Data MongoDB - Could not safely identify store assignment for repository candidate interface org.example.jpa.MyJpaRepository. If you want this repository to be a MongoDB repository, consider annotating your entities with one of these annotations: org.springframework.data.mongodb.core.mapping.Document (preferred), or consider extending one of the following types with your repository: org.springframework.data.mongodb.repository.MongoRepository.
    

    This makes sense because MyMongoDbRepository is not a JPA repository and MyJpaRepository is not a MongoDB repository. But it's still unnerving to see this message for each repository on startup. The only way to get rid of it is

    @EnableJpaRepositories("org.example.jpa")
    @EnableMongoRepositories("org.example.mongodb")
    

    somewhere in the Spring configuration. My question is, is that the expected behaviour?

    status: waiting-for-feedback status: waiting-for-triage 
    opened by sebastianhaberey 3
Releases(3.0.0)
Dynamically filters JPA entities with a simple query syntax. Provides JPA/Hibernate predicates and Spring Data specifications.

Spring Filter You need a way to dynamically filter entities without any effort? Just add me to your pom.xml. Your API will gain a full featured search

Turkraft 142 Dec 13, 2022
A lightweight messaging library that simplifies the development and usage of RabbitMQ with the AMQP protocol.

kryo-messaging This library contains a simple MessagingService which simplifies the setup and work with RabbitMQ and the AMQP protocol. Usage Gradle r

Kryonite Labs 3 Jan 10, 2022
An examples of creating test records in the database with Spring Boot + Spring Data + JPA usage.

Spring Boot + JPA — Clear Tests An examples of creating test records in the database with Spring Boot + Spring Data + JPA usage. Check out the article

Semyon Kirekov 8 Nov 24, 2022
Just-In-Time Access is an AppEngine application that lets you manage just-in-time privileged access to Google Cloud projects.

Just-In-Time Access Just-In-Time Access is an AppEngine application that lets you manage just-in-time privileged access to Google Cloud projects. Syno

Google Cloud Platform 36 Jan 3, 2023
In this project, we will implement two Spring Boot Java Web application called, streamer-data-jpa and streamer-data-r2dbc.

In this project, we will implement two Spring Boot Java Web application called, streamer-data-jpa and streamer-data-r2dbc. They both will fetch 1 million of customer's data from MySQL and stream them to Kafka. The main goal is to compare the application's performance and resource utilization.

Ivan Franchin 6 Nov 2, 2022
Application for creating blog posts, developed with Java using Spring Framework for backend and Angular along with PrimeNG Library for frontend development.

Application for creating blog posts, developed with Java using Spring Framework for backend and Angular along with PrimeNG Library for frontend development.

Áureo Carmelino 10 Nov 27, 2022
Projeto de LAB: Conhendo o projeto Spring data JPA com Java na prática

Conhecendo o Projeto Spring Data JPA na Prática Sejam bem-vindos ao projeto de LAB Conhecendo o Projeto Spring Data JPA na Prática oferecido gratuitam

Camila Cavalcante 130 Dec 31, 2022
This project shows how to configure basic auth to secure our rest API and basic transaction on Data JPA

Basic Atuthentication Spring Boot Data JPA, MySQL This project shows how to configure basic auth to secure our rest API and basic transaction on Data

Hafizullah Samim 1 Feb 10, 2022
Spring Boot JWT Authentication example with Spring Security & Spring Data JPA

Spring Boot JWT Authentication example with Spring Security & Spring Data JPA

null 1 Jan 26, 2022
An example of how to working with paging in Spring for GraphQL / Spring Data JPA

Spring for GraphQL Paging This repo contains the code for a live coding session I did on: Spring Data JPA GraphQL Paging & Sorting The reason I put th

Dan Vega 10 Nov 28, 2022
This repository contains source code examples to support my course Spring Data JPA and Hibernate Beginner to Guru

Spring Data JPA - Spring Data JPA This repository contains source code examples to support my course Spring Data JPA and Hibernate Beginner to Guru Co

John Thompson 8 Aug 24, 2022
Applied Spring Data JPA technologies including mapping, connecting real DB, Hibernate, Queries, Paging & Sorting, various Relationships, Transactions

University Management In this project, I practiced & applied Spring Data JPA technologies including mapping, connecting real DB, Hibernate, Queries, P

SarvarKhalimov 2 Sep 5, 2022
N-Layer Architecture human resource management system project with Java.

HRMS Project Backend N-Layer Architecture human resource management system project with Java. Report Bug · Request Feature About The Project Built Wit

Ahmet Çetinkaya 78 Dec 26, 2022
Model Layer Implementation for a J2EE Pull MVC WebApp

Modality is a lightweight but hightly configurable Java ORM, with a companion set of tools docs home modality-core doc modality-webapp doc velocity-to

Claude Brisson 11 Jan 3, 2023
Ethylene is a open-source, lightweight, general-purpose compatibility layer standing between the developer and the chaotic world of configuration file formats.

Ethylene Ethylene is a open-source, lightweight, general-purpose compatibility layer standing between the developer and the chaotic world of configura

Steank 7 Aug 9, 2022
An intelliJ plugin providing a UI layer for git-flow, which in itself is a collection of Git extensions to provide high-level repository operations for Vincent Driessen's branching model.

Git Flow Integration Plus for Intellij An intelliJ plugin providing a UI layer for git-flow, which in itself is a collection of Git extensions to prov

RubinCarter 35 Nov 8, 2022
springboot 框架与其它组件结合如 jpa、mybatis、websocket、security、shiro、cache等

致歉 由于自己懒以及身体对issuse 解决的不及时。请大家以后提issuse 的时候写清楚 模块名 比如“springboot-SpringSecurity4” 和问题,我会抽时间抓紧解决。 springboot-SpringSecurity0 包含两部分代码: 第一是 博客 springboot

abel 5.9k Jan 5, 2023
:herb: 基于springboot的快速学习示例,整合自己遇到的开源框架,如:rabbitmq(延迟队列)、Kafka、jpa、redies、oauth2、swagger、jsp、docker、spring-batch、异常处理、日志输出、多模块开发、多环境打包、缓存cache、爬虫、jwt、GraphQL、dubbo、zookeeper和Async等等:pushpin:

欢迎大家留言和PR~ Tip: 技术更新换代太快,本仓库仅做参考,自己的项目具体使用哪个版本还需谨慎思考~(不推荐使用最新的版本,推荐使用(最新-1|2)的版本,会比较稳定) spring-boot-quick 前言   自己很早就想搞一个总的仓库就是将自己平时遇到的和学习到的东西整合在一起,方便后

wangxc 2.1k Jan 2, 2023
以教学为目的的电商系统。包含ToB复杂业务、互联网高并发业务、缓存应用;DDD、微服务指导。模型驱动、数据驱动。了解大型服务进化路线,编码技巧、学习Linux,性能调优。Docker/k8s助力、监控、日志收集、中间件学习。前端技术、后端实践等。主要技术:SpringBoot+JPA+Mybatis-plus+Antd+Vue3。

简介 bcMall 是一个以教学为目的的电商系统。bcMall将为你展现一个典型的系统演进过程,所使用的主流技术完全开放。 它包含ToB复杂业务、互联网高并发业务、缓存应用;DDD、微服务指导。模型驱动、数据驱动。了解大型服务进化路线,编码技巧、学习Linux,性能调优。Docker/k8s助力、监

xjjdog 411 Jan 3, 2023