Spring Data JPA's dynamic query Specifications

The main structure:

 

 

Sometimes we query an entity when a given condition is not fixed, then you need to dynamically build the appropriate query, you can query the interface by JpaSpecificationExecutor in the Spring Data JPA. Compared JPQL, its advantage is type safety, more object-oriented.

java.util.List Import; 

Import org.springframework.data.domain.Page; 
Import org.springframework.data.domain.Pageable; 
Import org.springframework.data.domain.Sort; 
Import org.springframework.data.jpa.domain .Specification; 

/ ** 
 * JpaSpecificationExecutor method defined 
 ** / 
 public interface JpaSpecificationExecutor <T> { 
   	// query condition according to a target 
 	T the findOne (Specification <T> spec);	 
   	// set according to the conditions query 
 	List <T> findAll (Specification <T> spec); 
   	// The paging query condition 
 	Page <T> the findAll (Specification <T> spec, the Pageable Pageable); 
   	// sort query query 
 	List <T> findAll (Specification < T> spec, Sort sort) ; 
   	// statistical inquiry  
 	long count (Specification <T> spec );
}

         For JpaSpecificationExecutor, this interface is basically around Specification interface definition. We can simply be understood as, Specification query is constructed.

Only Interface Specification defines a method as follows:

// query construction 
    / ** 
    * the root: Root interface object represents the root of the query, may be obtained by the entity attributes the root 
    * Query: represents a top-level query object from a query definitions 
    * cb: used to build a query, this there are many conditions subject method 
    ** / 
    public Predicate toPredicate (root <T> root, CriteriaQuery Query, CriteriaBuilder cb <?>);

  spring configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/context HTTP: // the WWW .springframework.org / Schema / context / the Spring-context.xsd 
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd 
		HTTP: // http://www.springframework.org/schema/tx/spring-tx.xsd www.springframework.org/schema/tx 
		http://www.springframework.org/schema/data/jpa 
		HTTP: //www.springframework .org / Schema / Data / JPA / spring-jpa.xsd "> 

    <! - spring and spring data jpa configuration -> 

    <! - 1. Create an object to spring containers entityManagerFactory management -> 
    <the bean ID = "entityManagerFactoty" class = "org.springframework.orm.jpa .LocalContainerEntityManagerFactoryBean">
        <Property name = "the dataSource" REF = "the dataSource" /> 
        <-! scan package configuration (where the entity class package) -> 
        <Property name = "packagesToScan" value = "cn.itcast.domain" / > 
        <-! JPA implementations manufacturers -> 
        <Property name = "PersistenceProvider"> 
            <the bean class = "org.hibernate.jpa.HibernatePersistenceProvider" /> 
        </ Property> 

        <-! JPA adapter supplier - > 
        <Property name = "jpaVendorAdapter"> 
            <bean class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 
                <-! configure whether to automatically create database tables -> 
                <Property name = "generateDdl"= value "to false" /> 
                <-! Specifies the type of database -> 
                <Property name = "Database" value = "MYSQL Based" />
                <- Database dialect:! Supports unique grammar -> 
                <Property name = "databasePlatform" value = "org.hibernate.dialect.MySQLDialect" /> 
                <-! Whether SQL -> 
                <Property name = "showSql "value =" to true "/> 
            </ bean> 
        </ Property> 

        <- JPA dialect:! advanced features -> 
        <Property name =" JpaDialect "> 
            <bean class =" org.springframework.orm.jpa .vendor.HibernateJpaDialect "/> 
        </ Property> 

    </ bean> 

    <-!. 2 create a database connection pool -> 
    <bean the above mentioned id =" dataSource "class =" com.mchange.v2.c3p0.ComboPooledDataSource ">
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///jpa" ></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    </bean>

    <!--3.整合spring dataJpa-->
    <jpa:repositories base-package="cn.itcast.dao" transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactoty" ></jpa:repositories>

    <!--4.配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoty"></property>
    </bean>

    <!-- 4.txAdvice-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 5.aop-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* cn.itcast.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </ AOP: config> 


    <-. 5 declarative transaction! -> 

    <- 6. The configuration bundle Scan -!> 
    <context: Component Base-Package-Scan = "cn.itcast"> </ context: Scan-Component> 
</ Beans>

  

Individual cases query:

/ ** 
     * depending on the conditions, a single query objects 
     * / 
    @Test 
    public void testSpec () { 
        / * 
         * customize the query 
         * 1. Interface Specification implement (generic provide: a query object type) 
         * 2. The method implemented toPredicate (structure query) 
         * 3. the method of parameters required by the two parameters 
         * root: obtaining object attribute need, 
         * CriteriaQuery: constructing a query condition, inside the package a lot of query (fuzzy matching, the matching accuracy) 
         * 
         * case: according to the customer name, query the customer client named Jiege 
         * query 
         * 1. query 
         * cb objects 
         * 2. name property to compare 
         * root objects 
         * /
        Specification <the Customer> = new new Specification Specification <the Customer> () { 
            public toPredicate the Predicate (Root <the Customer> the root, a CriteriaQuery <?> Query, CriteriaBuilder CB) { 
                //. 1. Comparative acquired attribute 
                Path <Object> path = root.get ( "custName"); 
                // 2 configuration query select * from cust_customerwhere cust_name = 'Jiege' 
                / ** 
                 * the first parameter: comparison of the properties required (path object) 
                 * the second parameter: the current to be compared value 
                 * / 
                the Predicate the predicateA = cb.equal (path, "Jiege"); // for precise matching (comparison of properties: property value comparison) 

                return the predicateA; 
            } 
        };
        Customer customer = customerDao.findOne(specification);
        System.out.println(customer);
    }

 Case paging query:

/ ** 
     * Query tab 
     * Specification: query 
     * the Pageable: paging parameters 
     * paging parameters: the pages, the number of queries per page 
     * findAll (Specification, Pageable); conditionally paging query 
     * findAll (Pageable) No conditions tab 
     * Back Page (springDataJpa pageBean our packaged object data list, the number of total) 
     * / 
    @Test 
    public void testSpec4 () { 
        Specification Specification = null; 
        // PageRequest: object is an implementation of the interface class Pageable 
        / ** 
         * PageRequest in the process of creating, he needs to call the constructor with two arguments 
         * the first parameter: the number of pages of the current query (starting at 0) 
         * the second argument: the number of queries per page 
         * / 
        the Pageable = new new PageRequest the Pageable (0,2); 
        // paging query
        Page <the Customer> All = customerDao.findAll (null, Pageable); 
        System.out.println (all.getContent ()); // get the data set list 
        System.out.println (all.getTotalElements ()); // get the total number of 
        System.out.println (all.getTotalPages ()); // get the total number 


    }

 

   Note: You can refer to the structure, and some are omitted can be found in front of the inside.

 

Guess you like

Origin www.cnblogs.com/easyjie/p/12008161.html