Spring Data JPA初使用 *****重要********

Spring Data JPA初使用

  我們都知道Spring是一個非常優秀的JavaEE整合框架,它盡可能的減少我們開發的工作量和難度。

  在持久層的業務邏輯方面,Spring開源組織又給我們帶來了同樣優秀的Spring Data JPA。

  通常我們寫持久層,都是先寫一個接口,再寫接口對應的實現類,在實現類中進行持久層的業務邏輯處理。

  而現在,Spring Data JPA幫助我們自動完成了持久層的業務邏輯處理,我們要做的,僅僅是聲明一個持久層接口。

?

  1、下載開發所需要的發布包。

    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)其他一些依賴包可以從?http://ebr.springsource.com/repository/app/library?上查找下載

?

  2、新建一個Web項目 spring-data-jpa,把相應的jar包放到/WebRoot/WEB-INF/lib目錄下。

    我也沒有挑選哪些是不需要的,最后用到的jar如下:

復制代碼
antlr-2.7.7.jar com.springsource.net.sf.cglib-2.2.0.jar com.springsource.org.aopalliance-1.0.0.jar com.springsource.org.apache.commons.logging-1.1.1.jar com.springsource.org.aspectj.weaver-1.6.3.RELEASE.jar commons-lang3-3.1.jar dom4j-1.6.1.jar hibernate-commons-annotations-4.0.1.Final.jar hibernate-core-4.1.6.Final.jar hibernate-entitymanager-4.1.6.Final.jar hibernate-jpa-2.0-api-1.0.1.Final.jar javassist-3.15.0-GA.jar jboss-logging-3.1.0.GA.jar jboss-transaction-api_1.1_spec-1.0.0.Final.jar log4j-1.2.17.jar mysql-connector-java-5.0.4-bin.jar org.springframework.aop-3.1.2.RELEASE.jar org.springframework.asm-3.1.2.RELEASE.jar org.springframework.aspects-3.1.2.RELEASE.jar org.springframework.beans-3.1.2.RELEASE.jar org.springframework.context-3.1.2.RELEASE.jar org.springframework.context.support-3.1.2.RELEASE.jar org.springframework.core-3.1.2.RELEASE.jar org.springframework.expression-3.1.2.RELEASE.jar org.springframework.instrument-3.1.2.RELEASE.jar org.springframework.instrument.tomcat-3.1.2.RELEASE.jar org.springframework.jdbc-3.1.2.RELEASE.jar org.springframework.jms-3.1.2.RELEASE.jar org.springframework.js.resources-2.3.0.RELEASE.jar org.springframework.orm-3.1.2.RELEASE.jar org.springframework.oxm-3.1.2.RELEASE.jar org.springframework.test-3.1.2.RELEASE.jar org.springframework.transaction-3.1.2.RELEASE.jar org.springframework.web-3.1.2.RELEASE.jar org.springframework.web.portlet-3.1.2.RELEASE.jar org.springframework.web.servlet-3.1.2.RELEASE.jar slf4j-api-1.6.6.jar slf4j-log4j12-1.6.6.jar spring-data-commons-core-1.3.0.M1.jar spring-data-jpa-1.0.2.RELEASE.jar
復制代碼

  

  3、在MySql數據庫中建立一個叫spring_data_jpa的數據庫。

create database spring_data_jpa default character set utf8;

?

  4、JPA配置文件persistence.xml

    1)在src目錄下建立一個叫META-INF的文件夾

    2)在META-INF文件夾下建立persistence.xml文件

      persistence.xml內容如下:

復制代碼
<?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">                  <persistence-unit name="myJPA" transaction-type="RESOURCE_LOCAL">     <provider>org.hibernate.ejb.HibernatePersistence</provider>           <properties>             <!--配置Hibernate方言 -->             <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />             <!--配置數據庫驅動 -->             <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />             <!--配置數據庫用戶名 -->             <property name="hibernate.connection.username" value="root" />             <!--配置數據庫密碼 -->             <property name="hibernate.connection.password" value="root" />             <!--配置數據庫url -->             <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/spring_data_jpa?useUnicode=true&amp;characterEncoding=UTF-8" />             <!--設置外連接抓取樹的最大深度 -->             <property name="hibernate.max_fetch_depth" value="3" />             <!--自動輸出schema創建DDL語句 -->             <property name="hibernate.hbm2ddl.auto" value="update" />                 <property name="hibernate.show_sql" value="true" />             <property name="hibernate.format_sql" value="true" />             <property name="javax.persistence.validation.mode" value="none"/>         </properties>     </persistence-unit>              </persistence>
復制代碼

  

  5、Spring配置文件applicationContext.xml

   在src目錄下建立applicationContext.xml

   applicationContext.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:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:p="http://www.springframework.org/schema/p"       xmlns:cache="http://www.springframework.org/schema/cache"       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-3.1.xsd              http://www.springframework.org/schema/context              http://www.springframework.org/schema/context/spring-context-3.1.xsd              http://www.springframework.org/schema/aop              http://www.springframework.org/schema/aop/spring-aop-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/cache            http://www.springframework.org/schema/cache/spring-cache-3.1.xsd           http://www.springframework.org/schema/data/jpa           http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">                    <context:annotation-config />                    <context:component-scan base-package="cn.luxh.app"/>                 <!-- 定義實體管理器工廠 -->         <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">                <property name="persistenceUnitName" value="myJPA"/>         </bean>                    <!-- 配置事務管理器 -->              <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">               <property name="entityManagerFactory" ref="entityManagerFactory" />              </bean>                    <!-- 啟用 annotation事務-->             <tx:annotation-driven transaction-manager="transactionManager"/>                         <!-- 配置Spring Data JPA掃描目錄-->             <jpa:repositories base-package="cn.luxh.app.repository"/>                   </beans>
復制代碼

  

  6、web.xml

  web.xml內容如下:

復制代碼
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5"      xmlns="http://java.sun.com/xml/ns/javaee"      xmlns: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配置 -->   <context-param>     <param-name>webAppRootKey</param-name>     <param-value>springdatajpa.root</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>      <!-- 編碼過濾器 -->   <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>      <!-- 配置spring監聽器 -->   <context-param>     <param-name>contextConfigLocation</param-name>     <param-value>classpath:applicationContext.xml</param-value>   </context-param>   <listener>     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   </listener>      <!-- 配置緩存清除監聽器,負責處理由 JavaBean Introspector 功能而引起的緩存泄露 -->   <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、日志配置

    在src目錄下建立log4j.properties文件

    log4j.properties內容如下:

復制代碼
log4j.rootLogger=INFO,CONSOLE,FILE log4j.addivity.org.apache=true  # 應用于控制臺  log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender  log4j.appender.Threshold=INFO  log4j.appender.CONSOLE.Target=System.out  log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout  log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n  #log4j.appender.CONSOLE.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n  #應用于文件  log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender log4j.appender.FILE.File=${springdatajpa.root}/springdatajpa.log  log4j.appender.FILE.Append=true  log4j.appender.FILE.layout=org.apache.log4j.PatternLayout  log4j.appender.FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n 
復制代碼

  

  8、所有環境配完畢,開始寫一個Spring Data JPA 的增刪改查

    1)建立相應的包

???????????????????????????????????????????????

?

    2)領域模型實體類User

復制代碼
package cn.luxh.app.domain;  import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table;  /**  * 用戶信息  * @author Luxh  * 2012-8-30  */ @Entity @Table(name="t_user") public class User {          @Id     @GeneratedValue     private Integer id;          //賬號     private String account;          //姓名     private String name;          //密碼     private String password;               //省略 getter和setter方法  }
復制代碼

    3)聲明持久層接口UserRepository

    讓UserRepository接口繼承CrudRepository<T,ID>,T是領域實體,ID是領域實體的主鍵類型。CrudRepository實現了相應的增刪改查方法。

復制代碼
package cn.luxh.app.repository;   import org.springframework.data.repository.CrudRepository;  import cn.luxh.app.domain.User;  /**  * 用戶持久層接口  * @author Luxh  * 2012-8-31  */ public interface UserRepository extends CrudRepository<User,Integer>{           }
復制代碼

    不再需要持久層接口實現類。

?

    4)業務層

      一般多層架構是控制層調用業務層,業務層再調用持久層。所以這里寫個業務層。

      a、業務層接口:

復制代碼
package cn.luxh.app.service;  import cn.luxh.app.domain.User;  /**  * 用戶業務接口  * @author Luxh  * 2012-8-31  */ public interface UserService {          /**      * 保存用戶      * @param user      */     void saveUser(User user);          /**      * 根據id查找用戶      * @param id      * @return      */     User findUserById(Integer id);          /**      * 更新用戶      * @param user      */     void updateUser(User user);          /**      * 根據ID刪除用戶      * @param id      */     void deleteUserById(Integer id);           }
復制代碼

    b、業務層接口實現類

復制代碼
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;  /**  * 用戶業務服務實現類  * @author Luxh  * 2012-8-31  */ @Service("userService") public class UserServiceImpl implements UserService{               @Autowired     private UserRepository userRepository;//注入UserRepository      @Override     @Transactional     public void saveUser(User user) {         userRepository.save(user);              }      @Override     @Transactional(readOnly=true)     public User findUserById(Integer id) {         return userRepository.findOne(id);     }           @Override     @Transactional     public void updateUser(User user) {         userRepository.save(user);     }      @Override     @Transactional     public void deleteUserById(Integer id) {         userRepository.delete(id);     }  }
復制代碼

?

  9)編寫測試用例

    在執行測試的時候,發現如下錯誤:

復制代碼
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)     ... 51 more
復制代碼

  網上說是新版本的Hibernate跟javaee.jar里面的JPA接口沖突了。

  解決方法:移除MyEclipse自帶的Java EE 5 Libraries,自己新建一個user libraries,加入Java EE中的jsf-api.jar、jsf-impl.jar和jstl-1.2.jar,再加入Tomcat中自帶的     servlet-api.jar

????????????????????

        

       

       

       

?

  用servlet-api.jar替換掉javaee.jar就沒問題了。

  測試代碼:

復制代碼
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;          //保存用戶     @Test     public void testSaveUser() {         User user = new User();         user.setAccount("LiHuai");         user.setName("李壞");         user.setPassword("123456");                  userService.saveUser(user);     }               //根據id查找用戶     @Test     public void testFindUserById() {         Integer id = 1;         User user = userService.findUserById(id);         Assert.assertEquals("李壞",user.getName());     }          //更新用戶     @Test     public void testUpdateUser() {         Integer id = 1;         User user = userService.findUserById(id);         user.setName("李尋歡");                  userService.updateUser(user);              }          //根據id刪除用戶     @Test     public void testDeleteUserById() {         Integer id = 1;                  userService.deleteUserById(id);     }  }
復制代碼

?


  

  使用Spring Data JPA相當的簡單,我們只需要定義持久層的接口,不需要編寫實現代碼。

  步驟和注意點:

  1)在spring配置文件中添加倉庫接口的掃描路徑 <jpa:repositories base-package="cn.luxh.app.repository"/>

  2)編寫領域實體,需要按照JPA規范

  3)編寫倉庫Repository<T,ID>接口,依靠Spring Data規范定義接口方法。

     比如按照規范定義一個數據訪問接口方法? List<User> findByName(String name);

     Spring Data JPA 就會自動轉化為 select u from User u where u.name = ?1

  


?

  可以使用的倉庫接口有:
    Repository:           是 Spring Data的一個核心接口,它不提供任何方法,開發者需要在自己定義的接口中聲明需要的方法。

    CrudRepository:  ?       繼承Repository,提供增刪改查方法,可以直接調用。

    PagingAndSortingRepository:??? 繼承CrudRepository,具有分頁查詢和排序功能

    JpaRepository:???????????????????????? 繼承PagingAndSortingRepository,針對JPA技術提供的接口

    JpaSpecificationExecutor:????????? 可以執行原生SQL查詢

  

?

  

?

?

?

?

      

?

?

    

?

?

?

?

?

    

  

轉載于:https://www.cnblogs.com/daniell003/p/3529940.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273869.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273869.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273869.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

flask-筆記

-super() 使用super()保留基模板中定義的原始內容 - link標簽&#xff1a; 用來指定當前文檔和外部資源的關系。它最常見的是用來鏈接樣式表&#xff0c;也用來創建網站圖標(既是網站圖標樣式也包括移動設備和app圖標)。 -csrf: CSRF概念&#xff1a;CSRF跨站點請求偽造(…

MySQL 無法連接

Host localhost is not allowed to connect to this MySQL server 錯誤 解決辦法&#xff1a; C:\Program Files\MySQL\MySQL Server 5.5\my.ini 在[mysqld]下加下面兩行&#xff0c; skip-name-resolve skip-grant-tables 重啟mysql的windows服務&#xff0c;在mysql命令行界面…

能讓你少寫1000行代碼的20個正則表達式

參考: (1).http://www.codeceo.com/article/20-regular-expressions.html

http請求中的Query String Parameters、Form Data、Request Payload

參考: (1).(http請求參數之Query String Parameters、Form Data、Request Payload) - https://www.jianshu.com/p/c81ec1a547ad

蜜罐

http://www.projecthoneypot.org/home.php轉載于:https://www.cnblogs.com/diyunpeng/p/3534507.html

php中json_decode返回數組或對象的實例

1.json_decode() json_decode (PHP 5 > 5.2.0, PECL json > 1.2.0) json_decode — 對 JSON 格式的字符串進行編碼 說明 mixed json_decode ( string $json [, bool $assoc ] ) 接受一個 JSON 格式的字符串并且把它轉換為 PHP 變量 參數 json 待解碼的 json string 格式的…

如何精通js

參考: (1.)https://www.zhihu.com/search?typecontent&q%E5%A6%82%E4%BD%95%E7%B2%BE%E9%80%9Ajs

程序員怎么樣才能進入微軟?

程序員怎么樣才能進入微軟&#xff1f; 程序員到微軟中國總裁 “打工皇帝”長沙曬成功之道 程序員面試之道之走進微軟 應該是西北大學的學生&#xff0c;距離我好近&#xff08;我也在西安&#xff09;&#xff0c;可是又好遠&#xff08;人家拿到了MS的offer&#xff09;。 專…

python中的裝飾器-(重復閱讀)

---1--- 假設我們要增強某個函數的功能&#xff0c;比如&#xff0c;在函數調用前后自動打印日志&#xff0c;但又不希望修改某個函數的定義&#xff0c;這種在代碼運行期間動態增加功能的方式&#xff0c;稱之為“裝飾器”&#xff08;Decorator). 裝飾器本質上是一個Python…

[轉帖]好技術領導,差技術領導

團隊合作一個優秀的技術領導必然是團隊的一份子&#xff0c;他們認為當整個團隊成功時自己才稱得上成功。他們不僅要做好繁雜和不討好的本職工作&#xff0c;還要清除項目中的障礙&#xff0c;從而讓整個團隊能夠以100%的效率運轉起來。一個好的技術領導會努力拓寬團隊在技術上…

python有哪些常用的庫

參考: (1).https://www.zhihu.com/question/20501628/answer/19542741(Python 常用的標準庫以及第三方庫有哪些&#xff1f;)

C#打開文件對話框和文件夾對話框

打開文件對話框OpenFileDialog OpenFileDialog ofd new OpenFileDialog();ofd.Filter "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx|所有文件|*.*";ofd.ValidateNames true;ofd.CheckPathExists true;ofd.CheckFileExists true;if (ofd.ShowDialog() DialogResult.O…

debian安裝flash插件

$ sudo apt-get install flashplugin-nonfree 轉載于:https://www.cnblogs.com/vipzrx/p/3554839.html

python中的拷貝

1.賦值: 只是復制了新對象的引用&#xff0c;不會開辟新的內存空間。 2.淺拷貝: 創建新對象&#xff0c;其內容是原對象的引用。 淺拷貝有三種形式&#xff1a;切片操作&#xff0c;工廠函數&#xff0c;copy模塊中的copy函數。 如&#xff1a; lst [1,2,3,[4,5]] …

ZOJ 2112 Dynamic Rankings

這里是題目地址 其實就是帶修改的區間第K大。 寫了一下BIT套主席樹&#xff0c;內存飛起&#xff0c;似乎需要特別的優化技巧 所以還是寫了一下線段樹套平衡樹&#xff0c;跑了1s左右。 其實線段樹套平衡樹就是歸并樹的自然擴展而已。 歸并樹是把歸并排序的過程建成一顆線段樹…

python3[進階]8.對象引用、可變性和垃圾回收

文章目錄8.1變量不是盒子8.2 標識,相等性和別名8.2.1 在和is之間選擇8.2.2 元組的相對不可變性8.3 默認做淺復制&#xff08;拓展&#xff09;為任意對象做深復制和淺復制深拷貝和淺拷貝有什么具體的區別呢&#xff1f;8.4 函數的參數作為引用時8.4.1 不要使用可變類型作為參數…

openfire修改服務器名稱方法

1.登陸openfire管理頁面&#xff0c;在主頁面下方選擇編輯屬性&#xff0c;修改服務器名稱為當前主機名稱&#xff0c;點擊保存屬性&#xff0c;按頁面提示重啟服務器。 2.重啟后&#xff0c;主頁的服務器屬性下的服務器名稱出現一個嘆號&#xff0c;鼠標放上去顯示Found RSA c…

python (第八章)補充-可迭代對象(補充高階函數,以及常用的高階函數)

文章目錄可迭代對象迭代器什么是迭代器什么是生成器生成器的作用生成器的注意事項總結&#xff1a;高階函數什么是高階函數&#xff1f;map()函數filter()函數reduce()函數參考可迭代對象 我們已經知道&#xff0c;可以直接作用于for循環的數據類型有以下幾種&#xff1a; 一類…

網絡閱讀開篇

網絡閱讀也符合馬太效應&#xff0c;投入的時間越多&#xff0c;獲取的有效信息卻越來越少&#xff0c;因此做出以下規定&#xff1a; 1、限制網絡閱讀時間&#xff1b; 2、每次閱讀做總結。 本來想的挺簡單的&#xff0c;隨便搜了一下&#xff0c;居然一部小心拜讀了兩位大神的…

python (第二章)數據結構

文章目錄2.5 對序列使用 和 建立由列表組成的列表2.6序列的增量賦值&#xff08;和&#xff09;關于 的謎題補充&#xff1a;extend()方法和有什么區別呢&#xff1f;2.7 list.sort方法和內置函數sorted(排序)2.8 用bisect來管理已排序的序列2.8.2用bisect.insort插入元素2.9 當…