Spring Configuration JPA

Source: Internet
Author: User
Tags aop

Http://www.cnblogs.com/liuyitian/p/4062748.html Original Address

Objective:

  The JPA full name Java Persistence API, the Java Persistence API, provides Java developers with an object/relational mapping tool to manage relational data in Java applications, combined with the use of other Orm, to streamline the development process. Enable developers to focus on implementing their own business logic.

Spring JPA simplifies the creation of the JPA data access layer and the persistence layer functionality across storage, and the user's persistent layer DAO interface only needs to inherit his own defined (warehouse) interface, eliminating the need to write the implementation class, and can implement the object's CRUD operations, as well as paging sorting and other functions.

Before writing this chapter originally wanted to write a springmvc, later discovered that the JPA configuration can greatly simplify the MVC framework Configuration, first studies the spring Data JPA.

Preparatory work:

    •  Jar Package Support (needless to know, this chapter jar package will be placed on the 115 network disk for download)
    • Web. XML configuration (monitor loading of spring containers)
    • This chapter uses the Ali Connection pool (Druid), so the Web. XML has a related configuration
    • Spring container configuration (primarily beans and JPA)
    • Main configuration of JPA (entity class management, data source, connection pool, transaction, etc.)
    • Entity classes, persistence layer interfaces, creation of business layers
    • The test is placed in the next section (because the Springjunit unit test is used separately to explain)

First look at the package structure used in this chapter-for example:

  

Example code Demo:

Finally I will package the project in this chapter for download ************ comment section I'll explain as much as I can about ****************

Jar Package import ..... Slightly

Web. XML configuration

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id= "Webapp_ ID "version=" 3.0 "> <display-name>springMVC</display-name> <!--simultaneous loading of multiple spring profiles available--<conte xt-param> <param-name>contextConfigLocation</param-name> <param-value> CLASSPATH:SPR Ing-config/*.xml </param-value> </context-param> <!--spring Global monitoring--<listener> &lt ;listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener > <!--the druid default configuration, filter out the excess URL--<filter> &LT;FILTER-NAME&GT;DRUIDWEBSTATFILTER&LT;/FILTER-NAME&G    T <filter-class>com.alibaba.druid.support.http.webstatfilter</filter-class> <init-param> <param-name>exclusions</param-name> &LT;PARAM-VALUE&GT;*.J s,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value> </init-param> <init-param> <param-n Ame>principalsessionname</param-name> <param-value>_dest_login_</param-value> </ init-param> </filter> <filter-mapping> <filter-name>DruidWebStatFilter</filter-name> &L T;url-pattern>/*</url-pattern> </filter-mapping> <!--Statviewservlet is a standard servlet---< Servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>    Com.alibaba.druid.support.http.statviewservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </ servlet-mapping> <!--Spring Servlet, because the beans were all handed to Springjap, so SPRING-MVC inside nowis empty-<servlet> <servlet-name>springServlet</servlet-name> &LT;SERVLET-CLASS&GT;ORG.SPRINGFR Amework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name> Contextconfiglocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </ init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> &LT;SERVL Et-name>springservlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> & lt;! --Home--<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list ></web-app>

Spring-mvc.xml

<?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:context= "http://www.springframework.org/schema/ Context "xmlns:mvc=" Http://www.springframework.org/schema/mvc "    xsi:schemalocation="/http/ WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd/        http Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd        http ://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd " >    <!--Bean is configured in Spring-jpa.xml, so it is temporarily empty and is used to initialize the spring container--></beans>

Spring-jpa.xml

<?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:tx= "Http://www.springframework.org/schema/tx" Xmlns:cont       ext= "Http://www.springframework.org/schema/context" xmlns:jpa= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA"       xmlns:task= "Http://www.springframework.org/schema/task" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/ Spring-aop-3.1.xsd Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.1.xsd Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/ Spring-task-3.0.xsd Http://www.springframework.org/schema/context HTTP://WWW.springframework.org/schema/context/spring-context-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA http ://www.springframework.org/schema/data/jpa/spring-jpa.xsd "default-lazy-init=" true "> <description>sprin GJPA Configuration </description> <!--If spring uses JPA and the type is Localcontainerentitymanagerfactorybean, the component registration appears in this configuration file,  The rest of the configuration files can be ignored using component instead of annotation autoenrollment beans, and ensure that @required, @Autowired properties are injected \-and <context:component-scan Base-package= "COM.SPRING.JPA"/> <!--the properties file under the project path at spring startup, followed by ${key} to remove the corresponding value, so that the code can be decoupled and, subsequent only need to modify proper Ties file-<bean id= "Propertyplaceholderconfigurer" class= "            Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "> <property name=" Locations "> <list> <!--datasourse Connection pool related properties, the code is not posted here, it will be placed in a packaged project--<value>classpa Th:db.properties</value> </list> </property> </bean> <!--define the Entity Manager Factory JPA configuration localcontainerentitymanagerfactorybean This option spring plays the role of the container.           Completely in charge of JPA---point me to viewthree ways to generate entitymanagerfactory in spring    <bean id= "Entitymanagerfactory" class= "Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > <!--Specify data source-<property name= "DataSource" ref= "DataSource"/> <!--specify JPA Persistence implementation factory <property name= "Jpavendoradapter" ref= "Hibernatejpavendoradapter"/> <!--refer to Fixed entity class package path--<property name= "Packagestoscan" > <array> <value>c Om.spring.jpa</value> </array> </property> <!--specify JPA properties, such as specifying whether to display SQL in hibernate Display, dialect, etc.-<property name= "jpaproperties" > <props> <prop key= "Hibern Ate.dialect ">org.hibernate.dialect.Oracle10gDialect</prop> <prop key=" Hibernate.ejb.naming_stra Tegy ">org.hibernate.cfg.ImprovedNamingStrategy</prop> <prop key=" Hibernate.cache.provider_class ">org.hibernate.cache.nocacheprovider</prop> <prop key= "Hibernate.show_sql" >true</prop> <prop key= "Hi            Bernate.format_sql ">true</prop> <prop key=" Hibernate.hbm2ddl.auto ">validate</prop> </props> </property> </bean> <!--important configuration: Enable scanning and automatically create proxies-<jpa:rep Ositories base-package= "COM.SPRING.JPA" transaction-manager-ref= "TransactionManager" entity-manager-factory-ref= " Entitymanagerfactory "/> <!--hibernate implementation of JPA--<bean id=" Hibernatejpavendoradapter "class=" org.sp Ringframework.orm.jpa.vendor.HibernateJpaVendorAdapter "/> <!--JPA transaction Manager--<bean id=" Transactionmanag Er "class=" Org.springframework.orm.jpa.JpaTransactionManager "> <property name=" entitymanagerfactory "ref=" en Titymanagerfactory "/> </bean> <!--opening annotation transactions--<tx:annotation-driven transaction-manager=" Transa Ctionmanager "proxy-target-class="True"/> <!--data source configuration, using the in-app DBCP database connection pool--<bean id= "DataSource" class= "Com.alibaba.druid.pool.DruidDataS Ource "init-method=" Init "destroy-method=" Close "> <!--property name=" Driverclassname "value=" ${db.driverclass } "/--> <property name=" url "value=" ${db.jdbcurl} "/> <property name=" username "value=" ${db.user} "/> <property name=" password "value=" ${db.password} "/> <!--configuration initialization size, MIN, max--&LT;PR        Operty name= "InitialSize" value= "${db.initialsize}"/> <property name= "Minidle" value= "${db.minIdle}"/>  <property name= "maxactive" value= "${db.maxactive}"/> <!--configuration Get connection Wait timeout time--<property Name= "maxwait" value= "${db.maxwait}"/> <!--configuration interval to detect the idle connection that needs to be closed, in milliseconds--and <property name = "Timebetweenevictionrunsmillis" value= "${db.timebetweenevictionrunsmillis}"/> <!--Configure the minimum lifetime of a connection in a pool in milliseconds- <propertY name= "Minevictableidletimemillis" value= "${db.minevictableidletimemillis}"/> <property name= "ValidationQue Ry "value=" select ' x ' from dual "/> <property name=" Testwhileidle "value=" true "/> <property nam E= "Testonborrow" value= "false"/> <property name= "Testonreturn" value= "false"/> <!--open Pscache,         and specify the size of Pscache on each connection--<property name= "poolpreparedstatements" value= "${db.poolpreparedstatements}"/> <property name= "maxpoolpreparedstatementperconnectionsize" value= "${ Db.maxpoolpreparedstatementperconnectionsize} "/> </bean> <!--start support for @aspectj (facet-oriented) annotations--&lt ; Aop:aspectj-autoproxy/> </beans>

After configuring the configuration file, we should write the corresponding entity class, Dao, and service, here are the simple 3 classes:

User entity class

Package Com.spring.jpa.user;import Javax.persistence.column;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.id;import Javax.persistence.sequencegenerator;import javax.persistence.table;/** * User entity class * @author Liuyt * @date 2014-10-30 pm 2:27:37 */@Entity @table (name= "T_springjpa_use R ") public class User {/** * primary key sequence: Default_suquence is a sequence I created in the Oracle database * My_suquence is to create a reference name for a custom sequence     Called * refers to my primary key generation strategy my_suquence is using the default_suquence sequence. */@SequenceGenerator (name = "My_suquence", Sequencename = "default_suquence") @Id @GeneratedValue (generator= "My_        Suquence ") Private Long ID;        @Column (name= "user_name") private String userName;    @Column (name= "User_password") private String PASSWORD;    /*************get****************set***************/public Long getId () {return id;    } public void SetId (Long id) {this.id = ID; } public String GetUserName () {RetuRN UserName;    } public void Setusername (String userName) {this.username = UserName;    } public String GetPassword () {return passWord;    } public void SetPassword (String passWord) {This.password = PassWord;                } @Override Public String toString () {return "User [id=" + ID + ", username=" + UserName + ", password="    + PassWord + "]"; }}
User Entity

Iuserdao Persistence layer (JPA's core foundation for persistence layer simplification)

Package Com.spring.jpa.user;import Org.springframework.data.repository.pagingandsortingrepository;import org.springframework.stereotype.repository;/** * Persistent Layer interface * @author Liuyt * @date 2014-10-30 pm 2:09:48 */@Repositorypublic in Terface Iuserdao extends Pagingandsortingrepository<user, long>{/** * As you can see from the previous configuration, Spring's support for JPA is already very strong and developers     No need to pay much attention to Entitymanager's creation, transaction processing, and other JPA-related processing * ***********************************************************************                                    * However, Spring's support for JPA is more than that, it fundamentally simplifies our business code * * When using JPA support, our code should look like this: * * 1, Iuserdao persistent Layer interface * * 2, Iuserdaoimpl Long-Layer Implementation class * * 3, Iuserservice business Layer interface ..... Not listed later * * Each write an entity class, will be derived from 5, 6 classes to operate on him, even with annotations, we can rely on the injection method to get the implementation class, * * But the General Cru D, and so on, you say, I can define a parent class, using the generic reflection principle, * *But then you also need to declare your own implementation class for each DAO to inherit your parent class * * ************************************************* * So the problem comes ...      (not excavator technology) simplified technology for durable layers which is strong?                                                            Spring Data JPA * * The only thing you need to do is declare the persistence layer interface to inherit the persistent layer interface that he has encapsulated, just like this class of Iuserdao * * Available interfaces are: * Repository: is a core interface of Spring data, it does not provide any method, the developer needs to define the The required method is declared in the interface.                            * * Crudrepository: Inherit repository, provide the method of adding and deleting, can call directly.                         * * Pagingandsortingrepository: Inherit crudrepository, with paging query and sorting function (this class instance) * * Jparepository: Inherit Pagingandsortingrepository, interface provided for JPA technology * * Jpaspecificationexecutor: can execute native SQL                            Query * * Inherits different interfaces, there are two different generic parameters, they are class objects and primary key types for this persistence layer operation. **     *********************************************************************************     */}

In order to facilitate the demonstration, we do not write the business layer interface, directly on the Business Layer Service code

UserService Business Layer

Package Com.spring.jpa.user;import Java.util.list;import Javax.annotation.resource;import Org.springframework.data.domain.page;import Org.springframework.data.domain.pagerequest;import org.springframework.stereotype.service;/** * User business layer, dependent on persistent layer Iuserdao * @author Liuyt * @date 2014-10-30 pm 2:37:21 */@Serv        Icepublic class UserService {//recommended to replace Autowrite annotations with Resource @Resource private Iuserdao Userdao;    Added user public void Saveuser (user user) {userdao.save (user);    }//delete user, parameter can also be a user object containing ID public void DeleteUser (Long id) {userdao.delete (ID); }//Query All User objects, findone to query a single public list<user> findallusers () {return (list<user>) userdao.f    Indall (); /** * Query the user collection based on a paged object (you can also add a store sort property) * Pagerequest is the spring's own encapsulated request paging class that implements the Pageable interface, which includes the paging property obtained from the request (when Previous page and size) and get method * by invoking the paging method, a Page<> object with a generic collection is returned, which contains the various properties and result sets computed through the query * Detailed class structure and properties see source * @param page * @ return */Publicpage<user> findalluserbypage (Pagerequest page) {return (page<user>) userdao.findall (page); }}

At this point, the overall SPRINGJPA framework is set up, the rest is to write the page and the controller to test, here is not to do the demonstration, because the next chapter will use the Springunit unit test, through the method of annotations to test, details please step: to be updated ...

Project War Package Download: Click I download

Summarize:

    •  It may be a headache to import jar packages during the learning period, because jars of various frameworks can sometimes be incompatible ( Click to download this chapter jar package ) to expire please remind
    • This chapter uses the Druid Connection pool configuration, the detailed configuration please the asynchronous degree Niang
    • Spring-jpa.xml can be used for different needs, can choose different Entitymanagerfactory entity class management
    • Don't forget the configuration of the <jpa:repositories/> Tag, which he used to declare the package path that JPA involves
    • SPRINGJPA integrates declarative transactions, remember to turn on annotation transactions
    • There are a number of implementations of the persistence layer that are flexible to the requirements (this chapter shows the interface for paging, because the interface is roughly described on the web)
    • Not covered: Additional features: such as query queries, the new DAO interface method

Spring configuration JPA (RPM)

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.