Spring Data JPA Framework

Source: Internet
Author: User
Tags aop
Spring Data Framework

The Spring Data project is designed to simplify the construction of data access technologies based on the Spring framework application and is a comprehensive data-tier solution provided by spring. (or you can encapsulate a solution for other persistence layer solutions). It supports relational database, non relational database, map-reduce framework, cloud data service and so on.
Spring Data JPA is a module of the spring data framework.
Spring data JPA relies on the core JAR,JPA of spring with only interfaces and annotations, and the functionality implementation of Spring data JPA is hibernate, It is therefore also necessary to introduce hibernate support (Consolidation) project Hibernate-entitymanager for JPA. using the JPA Hibernate implementation version

For JPA interface programming, the bottom of the default is to use the hibernate implementation.
Development steps:
-Independent development JPA needs to be established in SRC Meta-inf folder, inside the Persistence.xml (JPA core configuration files, similar to hibernate.cfg.xml)
-Configuration file Persistence.xml content: slightly
-Java code: slightly

JPA programming is through Entitymanagerfactory (similar to sessionfactory), obtain Entitymanager (similar session) for the increase of the check, the crud methods are:
Add persist (), modify merge (), delete remove (), query Find () spring Data JPA Configuration and basic use of spring consolidation JPA configuration

Configure Entitymanagerfactory, configure transactions, configure JPA scans, and introduce namespaces.

Development steps:
Configures Entitymanagerfactory (similar to sessionfactory) and transactions.
-Use the Localcontainerentitymanagerfactorybean provided by spring to consolidate JPA, get entitymanagerfactory;
- Transactions are managed through Jpatransactionmanager and need to be injected entitymanagerfactory

    <!--entity Management factory--> <bean id= "entitymanagerfactory" class= "Org.springframework.orm.jpa.LocalContainerEntityMa"
            Nagerfactorybean "> <!--data source--> <property name=" DataSource "ref=" DataSource "/>
            <!--scan entity class--> <property name= "Packagestoscan" value= "Cn.aric.bos.domain"/> &LT;!-JPA supplier Matching: Database and dialect--> <property name= "Jpavendoradapter" > <bean class= "Org.spri" Ngframework.orm.jpa.vendor.HibernateJpaVendorAdapter > <!--database type configuration--> & Lt;property name= "Database" value= "ORACLE"/> <!--whether to automatically generate DDL-built tables--> Operty name= "Generateddl" value= "true"/> <!--configuration dialect dialect--> <proper
                    Ty name= "Databaseplatform" value= "Org.hibernate.dialect.Oracle10gDialect"/> <!--print SQL--> <prOperty name= "Showsql" value= "true"/> </bean> </property> <!--configuration
                    Hibernate other properties--> <property name= "Jpaproperties" > <props>
    <prop key= "Hibernate.format_sql" >true</prop> </props> </property> </bean> <!--transaction manager--> <bean id= "TransactionManager class=" org.springframework.orm.jpa.JpaTransact Ionmanager "> <property name=" entitymanagerfactory "ref=" entitymanagerfactory "/> </bean> &l t;!
 --Registered driver--> <tx:annotation-driven transaction-manager= "TransactionManager"/>
repository development of Spring Data JPA

Spring Data JPA consolidates JPA (write DAO interface + configuration Scan-engagement mechanism-it's consolidated is equivalent to 0 configurations).
The Spring Data JPA is programmed in a different way than before. You do not need to write the implementation class, just write the interface.
Its DAO (Repository) has written the default implementation class, and for most general-purpose functions, we just need to provide the interface to use.
How to use: we build an interface that inherits any of the following interfaces to use the functionality that is provided in-house.

The DAO interface writes rules:
-Repository (Null interface)
-Crudrepository (add to check)
-Pagingandsortingrepository (Paging and sorting)
-Jparepository (extended additions, deletions, bulk operations)
-Jpaspecificationexecutor (interface for query)
-Specification: A query specification provided by spring Data JPA for complex queries.

Development:
-Your own interface inherits directly from Jparepository
-Do not need to write implementation, because the Simplejparepository has implemented a general deletion and change, and querydsljparepository implementation of special, extended functions.

    User Action DAO public
    Interface Userdao extends Jparepository<user, string> {

    }
Test

1. Inject Bean:
When DAO is managed by spring data, there is no need to add @repository annotations (or add them because there are no implementation classes) on DAO.
Configure the DAO scan in Applicationcontext.xml, which automatically scans the class that inherits the Repository interface as a spring bean. The DAO can be injected into the service.

2. To introduce the configuration code for the namespace:

    <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:aop=" http:// Www.springframework.org/schema/aop "xmlns:tx=" Http://www.springframework.org/schema/tx "xmlns:jpa=" http:// WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:// Www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http:// Www.springframework.org/schema/context/spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http:// Www.springframework.org/schema/aop/spring-aop.xsd Http://www.springframework.org/schema/tx Http://www.springfram Ework.org/schema/tx/spring-tx.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA http://www.springframework.org/ Schema/data/jpa/spring-jpa.xsd "> <!--service needs Spring Scan--> <Context:component-scan base-package= "Cn.aric.bos.service,cn.aric.bos.web"/> <!--
 DAO needs to be springdata Scan Management to automatically scan all inherited repository interfaces--> <jpa:repositories base-package= "Cn.aric.bos.dao"/>

Spring junit Integration Test repository extended customization Capabilities

The Spring Data JPA built-in repository has provided a way to change and delete the search:
-Add, modify-save methods (save all fields or modify all fields-saveorupdate, single table: Bottom, if there is a value of ID, will automatically send query statement FindByID, and then judge if there is in the database, then update, if not, insert)
-delete--delete method
-Querying a single data--findone method (FindByID)
-Query all data--findall method 1.Spring The attribute expression (property expressions)

Define a method, the method name conforms to a certain rule, can build the query statement, the result will automatically encapsulate according to the return type. You don't need to implement a method, just define it.
Rationale: Spring Data JPA uses a called property expressions to automatically query against a property as a condition.
Syntax rules for property expressions: Method names must meet: FindBy property names (field name parameters)
If you have multiple attribute conditions or property conditions that are not equal, you can use some keywords (see official specification documentation), which is also called JPQL syntax. The method simply satisfies the method naming rules (note case) and automatically generates JPQL statements.

    /** *
     @param username
     * @return/Public user
    Findbyusername (String username)

    based on user name; /**
     * Login Query
     * @param user
     * @return
    /Public user login (user user);
2.JPA named query (JPA namedqueries)

Advantages: can be flexible to write SQL or HQL, to achieve arbitrary query.
Disadvantage: You need to write SQL or HQL, and the statements and query methods are not closely related to programming.

There are two ways of writing and configuring:
-Use annotation development, you need to use JPA annotation @namequery (HQL) or @namednativequery (SQL) to customize named queries on entity classes;
-Using XML for development, you need to customize named queries in Hbm.xml.
Spring Data JPA automatically invokes the statement to execute the query. The name of a named query must meet the following rules: Entity class name. Method Name.

    Spring Data JPA automatically looks for  entity class names. Method name User.findpasswordbyusername public
    string Findpasswordbyusername (string username);

    @Entity
    @Table (name= "T_user", schema= "bos")
    @NamedQueries ({@NamedQuery (name=) User.findpasswordbyusername ", query=" select password from User where username=? ")})
    public class User {

    }
@query annotation for 3.Spring Data JPA

Advantages: The query itself is linked to the way in which they are executed.
Disadvantages: Also write SQL or HQL

The programming method is to write the statement directly on the method by @query annotation, whose parameter is the JPQL statement. (similar to Hibernate hql or SQL)

//query Annotation Anonymous parameter query//@Query (value= "Select password from User where username =? 1")//HQL syntax @Query (value= "sel ECT password from T_user where username =? ", nativequery=true)//sql syntax public string findpasswordbyusername (string user

    name); Named parameter query @Query in query annotation ("Select u from User u where u.username =:username or U.password =:p assword") Public User
Findbyusernameorpassword (@Param ("username") string username, @Param ("password") string password); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.