We all know that spring is a very good Java EE Integration Framework that minimizes the effort and difficulty of our development.
In the business logic of the persistence layer, the spring open source organization has also brought us the same excellent spring Data JPA.
Usually we write the persistence layer, is to write an interface, and then write the interface corresponding to the implementation class, in the implementation class for the persistence layer of business logic processing.
Now, Spring Data JPA helps us automate the processing of the business logic of the persistence layer, and all we have to do is declare a persistent layer interface.
1, download the development of the required release package.
1) Spring-framework-3.1.2.release-with-docs.zip
: Http://www.springsource.org/spring-framework
2) Hibernate-release-4.1.6.final.zip
: Http://olex.openlogic.com/packages/hibernate
3) Spring Data JPA
Spring Data JPA
: HTTP://WWW.SPRINGSOURCE.ORG/SPRING-DATA/JPA
Spring Data Commons
: http://www.springsource.org/spring-data/commons
4) Some other dependent packages can be found on the http://ebr.springsource.com/repository/app/library from the download
2, create a new WEB project SPRING-DATA-JPA, put the corresponding jar package into the/webroot/web-inf/lib directory.
I also did not pick which ones were not needed, and the last jars used were as follows:
Antlr-2.7.7.jarcom.springsource.net.sf.cglib-2.2.0.jarcom.springsource.org.aopalliance-1.0.0.jarcom.springsource.org.apac He.commons.logging-1.1.1.jarcom.springsource.org.aspectj.weaver-1.6.3.release.jarcommons-lang3-3.1.jardom4j-1.6.1.jarhibe Rnate-commons-annotations-4.0.1.final.jarhibernate-core-4.1.6.final.jarhibernate-entitymanager-4.1.6.final.jarhibernate-j Pa-2.0-api-1.0.1.final.jarjavassist-3.15.0-ga.jarjboss-logging-3.1.0.ga.jarjboss-transaction-api_1.1_ Spec-1.0.0.final.jarlog4j-1.2.17.jarmysql-connector-java-5.0.4-bin.jarorg.springframework.aop-3.1.2.release.jarorg.spring Framework.asm-3.1.2.release.jarorg.springframework.aspects-3.1.2.release.jarorg.springframework.beans-3.1.2.release.jaror g.springframework.context-3.1.2.release.jarorg.springframework.context.support-3.1.2.release.jarorg.springframework.core- 3.1.2. Release.jarorg.springframework.expression-3.1.2.release.jarorg.springframework.instrument-3.1.2.release.jarorg.springfram Ework.instrument.tomcat-3.1.2.release.jarorg.sPringframework.jdbc-3.1.2.release.jarorg.springframework.jms-3.1.2.release.jarorg.springframework.js.resources-2.3.0.rele Ase.jarorg.springframework.orm-3.1.2.release.jarorg.springframework.oxm-3.1.2.release.jarorg.springframework.test-3.1.2.r Elease.jarorg.springframework.transaction-3.1.2.release.jarorg.springframework.web-3.1.2.release.jarorg.springframework.w Eb.portlet-3.1.2.release.jarorg.springframework.web.servlet-3.1.2.release.jarslf4j-api-1.6.6.jarslf4j-log4j12-1.6.6.jarsp Ring-data-commons-core-1.3.0.m1.jarspring-data-jpa-1.0.2.release.jar
3. Create a database called SPRING_DATA_JPA in the MySQL database.
Create DATABASE SPRING_DATA_JPA default character set UTF8;
4. JPA configuration file Persistence.xml
1) Create a folder called Meta-inf in the SRC directory
2) Create the Persistence.xml file under the Meta-inf folder
Persistence.xml content is as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><persistence version= "2.0" xmlns= "http://java.sun.com/xml/ns/ Persistence "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://java . sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd "> < ;p ersistence-unit name= "MYJPA" transaction-type= "resource_local" > <provider> Org.hibernate.ejb.hibernatepersistence</provider> <properties> <!--configuring Hibernate dialect--- <property name= "Hibernate.dialect" value= "Org.hibernate.dialect.MySQL5Dialect"/> <!--configuration data Library driver-<property name= "Hibernate.connection.driver_class" value= "Com.mysql.jdbc.Driver"/> <!--Config database user name--<property name= "Hibernate.connection.username" value= "root"/> <!-- Configure the database password--<property name= "Hibernate.connection.passwoRd "value=" root "/> <!--configuration database URL--<property name=" Hibernate.connection.url "value=" JD Bc:mysql://localhost:3306/spring_data_jpa?useunicode=true&characterencoding=utf-8 "/> <!--set up outside connection fetching Maximum depth of tree--<property name= "hibernate.max_fetch_depth" value= "3"/> <!--Auto Output schema to create DDL statements --<property name= "Hibernate.hbm2ddl.auto" value= "Update"/> <property name= "Hiber Nate.show_sql "value=" true "/> <property name=" Hibernate.format_sql "value=" true "/> <pr Operty name= "Javax.persistence.validation.mode" value= "None"/> </properties> </persistence-unit> </persistence>
5. Spring configuration file Applicationcontext.xml
Build applicationcontext.xml in src directory
Applicationcontext.xml content is as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmln s:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:p= "H ttp://www.springframework.org/schema/p "xmlns:cache=" Http://www.springframework.org/schema/cache "xmlns:jpa=" htt P://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA "xsi:schemalocation=" Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/C Ontext http://www.springframework.org/schema/context/spring-context-3.1.xsd Http://www.springframe WORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.spring Framework.org/schema/tx Http://www.springframework.org/schema/tx/spring-tx-3.1.xsd Http://www.springframework.org/schema/cach E http://www.springframework.org/schema/cache/spring-cache-3.1.xsd Http://www.springframework.org/schem A/DATA/JPA http://www.springframework.org/schema/data/jpa/spring-jpa.xsd "> <context:annota Tion-config/> <context:component-scan base-package= "Cn.luxh.app"/> <!--define entity management Factory--<bean id= "entitymanagerfactory" class= "Org.springframework.orm.jpa.LocalContainerEntityManagerFactor Ybean "> <property name=" persistenceunitname "value=" MYJPA "/> </bean> <!--configuration transaction Manager-<bean id= "TransactionManager" class= "Org.springframework.orm.jpa.JpaTransactionManag Er "> <property name=" entitymanagerfactory "ref=" Entitymanagerfactory "/> </bean> <!--KaiWith annotation transaction--<tx:annotation-driven transaction-manager= "TransactionManager"/> <!--Configure Spring Data JPA Scan Directory--<jpa:repositories base-package= "Cn.luxh.app.repository"/> </beans>
6. Web. xml
The Web. Xml reads as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" XM Lns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http:/ /java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <display-name></display-name> <!--log4j configuration-- <context-param> <param-name>webAppRootKey</param-name> <param-value>springdatajpa.root& lt;/param-value> </context-param> <context-param> <param-name>log4jconfiglocation</ Param-name> <param-value>classpath:log4j.properties</param-value> </context-param> < Listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </ listener> <!--coded Filters--<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.chaRacterencodingfilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </ Filter-mapping> <!--Configure Spring Listener--<context-param> <param-name>contextconfiglocation</par Am-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> < Listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--Configure cache cleanup Listener to handle cache leaks caused by JavaBean introspector functionality-<listener> <listener -class>org.springframework.web.util.introspectorcleanuplistener</listener-class> </listener> < Welcome-file-list> <WELCOME-FILE>index.jsp</welcome-file> </welcome-file-list></web-app>
7. Log Configuration
Build the Log4j.properties file in the SRC directory
Log4j.properties content is as follows:
8, all the environment is complete, began to write a spring Data JPA additions and deletions to search
1) Set up the appropriate package
2) domain model entity class user
Package Cn.luxh.app.domain;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.id;import javax.persistence.table;/** * User information * @author LUXH * 2012-8-30 */@Entity @table (name= "T_user" public class User { @Id @GeneratedValue private Integer Id; Accounts private String account; Name private String name; Password private String password; Omit getter and Setter methods}
3) Declaring persistent layer interface Userrepository
Let the Userrepository interface inherit crudrepository<t,id>,t is the domain entity, and the ID is the primary key type of the domain entity. Crudrepository realized the corresponding adding and deleting methods.
Package Cn.luxh.app.repository;import Org.springframework.data.repository.crudrepository;import cn.luxh.app.domain.user;/** * User Persistence Layer Interface * @author LUXH * 2012-8-31 */public interface Userrepository extends crudrepository& Lt user,integer>{ }
The persistence layer interface implementation class is no longer required.
4) Business Layer
The general multilayer architecture is the control layer called the business layer, and the business layer calls the persistence layer again. So write a business layer here.
A, the business layer interface:
Package Cn.luxh.app.service;import cn.luxh.app.domain.user;/** * User Business interface * @author LUXH * 2012-8-31 */public interface User Service { /** * Save user * @param user * /void Saveuser (user user); /** * Find the user by ID * @param ID * @return * /user Finduserbyid (Integer ID); /** * Update users * @param user * /void UpdateUser (user user); /** * Delete User * @param ID * /void Deleteuserbyid (Integer ID) by ID; }
B, Business layer interface implementation class
Package Cn.luxh.app.service;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Org.springframework.transaction.annotation.transactional;import Cn.luxh.app.domain.user;import cn.luxh.app.repository.userrepository;/** * User Business Service Implementation class * @author LUXH * 2012-8-31 */@ Service ("UserService") public class Userserviceimpl implements userservice{@Autowired private userrepository userrepository;//inject userrepository @Override @Transactional public void saveuser (user user) {Userreposito Ry.save (user); } @Override @Transactional (readonly=true) public User Finduserbyid (Integer ID) {return userrepository.fin Done (ID); } @Override @Transactional public void updateUser (user user) {userrepository.save (user); } @Override @Transactional public void Deleteuserbyid (Integer id) {userrepository.delete (ID); }}
9) Writing Test Cases
When performing the test, the following error was found:
caused By:java.lang.NoSuchMethodError:javax.persistence.spi.PersistenceUnitInfo.getValidationMode () ljavax/ Persistence/validationmode; At Org.hibernate.ejb.Ejb3Configuration.configure (ejb3configuration.java:633) at Org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory (hibernatepersistence.java:73) At Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory ( localcontainerentitymanagerfactorybean.java:268) at Org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet ( abstractentitymanagerfactorybean.java:310) at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods ( abstractautowirecapablebeanfactory.java:1514) at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( abstractautowirecapablebeanfactory.java:1452) ... Wuyi more
Online says the new version of Hibernate is in conflict with the JPA interface inside the Javaee.jar.
Workaround: Remove myeclipse Java EE 5 Libraries, create a new user Libraries, join the Jsf-api.jar in Java EE, Jsf-impl.jar and Jstl-1.2.jar, then join the Servlet-api.jar that comes with Tomcat
Replacing Javaee.jar with Servlet-api.jar is no problem.
Test code:
Package Cn.luxh.app.test;import Org.junit.assert;import Org.junit.test;import org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import Cn.luxh.app.domain.user;import Cn.luxh.app.service.UserService, @RunWith (springjunit4classrunner.class) @ContextConfiguration ({"/ Applicationcontext.xml "}) public class Usertest {@Autowired private userservice userservice; Save user @Test public void Testsaveuser () {User user = new user (); User.setaccount ("Lihuai"); User.setname ("Lee Bad"); User.setpassword ("123456"); Userservice.saveuser (user); }//Find the user by ID @Test public void Testfinduserbyid () {Integer id = 1; User user = Userservice.finduserbyid (ID); Assert.assertequals ("Li Bad", User.getname ()); }//update user @Test public void TestUpdateUser () {Integer id = 1; User user = Userservice.finduserbyid (ID); User.setname ("Li Xun Huan"); Userservice.updateuser (user); }//delete user @Test public void Testdeleteuserbyid () {Integer id = 1 based on ID; Userservice.deleteuserbyid (ID); }}
Using spring Data JPA is fairly straightforward, and we just need to define the interface for the persistence layer, without having to write implementation code.
Steps and note points:
1) Add a scan path to the warehouse interface in the spring configuration file <jpa:repositories base-package= "Cn.luxh.app.repository"/>
2) Write domain entities that need to follow the JPA specification
3) write the warehouse repository<t,id> interface and define the interface method by the spring data specification.
For example, define a data access interface method according to the specification list<user> Findbyname (String name);
Spring Data JPA is automatically converted to select u from User u where u.name =? 1
The warehouse interfaces that you can use are:
Repository: is a core interface of Spring data that does not provide any methods, and developers need to declare the required methods in their own defined interfaces.
Crudrepository: Inherit repository, provide the method of adding and deleting, can call directly.
Pagingandsortingrepository: Inherit crudrepository, with paging query and sort function
Jparepository: Inherited Pagingandsortingrepository, interface provided for JPA technology
Jpaspecificationexecutor: Can execute native SQL query
Spring Data JPA First Use (reprint)