1. 程式人生 > >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  

    2)hibernate-release-4.1.6.Final.zip

    3)Spring Data JPA

      Spring Data JPA

      Spring Data Commons

  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)編寫測試用例

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

相關推薦

Spring Data jpa搭建+配置

     我們都知道Spring是一個非常優秀的JavaEE整合框架,它儘可能的減少我們開發的工作量和難度。   在持久層的業務邏輯方面,Spring開源組織又給我們帶來了同樣優秀的Spring Data JPA。   通常我們寫持久層,都是先寫一個介面,再寫介面對應

SpringSpring MVC原理及配置

進行 return sub sca scrip uil 線程安全 松耦合 必須 1.Spring MVC概述: Spring MVC是Spring提供的一個強大而靈活的web框架。借助於註解,Spring MVC提供了幾乎是POJO的開發模式,使得控制器的開發和測試更加簡

Spring MVC原理及配置

對象 classpath oca entity attribute nco conf nal spring Spring MVC原理及配置 1.Spring MVC概述: Spring MVC是Spring提供的一個強大而靈活的web框架。借助於註解,Spring MVC提

spring boot application properties配置

ini let encoding odi gap pool nodes gui erp # =================================================================== # COMMON SPRING BOOT

Spring 入門 web.xml配置

.net .html tle spring tail pri .com http https Spring 入門 web.xml配置詳解 https://www.cnblogs.com/cczz_11/p/4363314.html https://blog.csdn.ne

Spring-boot入門之配置

1.配置檔案 spring-boot預設有兩種配置檔案 appliation.properties appliation.yml 配置檔案預設放在src/main/resources目錄或者是類路徑/config下 配置檔案的作用:修改sprin

Spring-Security整合CAS之Spring-Security.xml部分配置

<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://w

阿里雲輕量應用伺服器 搭建配置

好久沒有更新部落格了,說來也是慚愧沒有養成記錄經驗的習慣。 有很多技術開發同學都想擁有自己的伺服器用來搭建個人網站,或者展示作品,但是怕租上不會配置或者嫌配置繁瑣難下決定。 廢話不多說直接進入正題,前兩天幫朋友配置一臺阿里雲的輕量應用伺服器(注意不是雲伺服器ECS但是大同小異)。 伺服器規格

(轉)Spring boot——logback.xml 配置(二)

回到頂部1 根節點<configuration>包含的屬性scan:當此屬性設定為true時,配置檔案如果發生改變,將會被重新載入,預設值為true。scanPeriod:設定監測配置檔案是否有修改的時間間隔,如果沒有給出時間單位,預設單位是毫秒。當scan為true時,此屬性生效。預設的時間間隔

Spring data jpa怎麼配置一個實體類對映兩張資料庫表

今天寫一個Spring boot整合Spring data jpa實現一些簡單功能的技術驗證專案,其中一個Model類Wel映射了“T_PM_WELL”表,但有一個屬性"sname"需要對映到第二張表“T_PM_NODE”上,開始時用@Formula註解來實現,但執行時總是

spring security oauth2.0配置

spring security oauth2.0 實現 目標 現在很多系統都支援第三方賬號密碼等登陸我們自己的系統,例如:我們經常會看到,一些系統使用微信賬號,微博賬號、QQ賬號等登陸自己的系統,我們現在就是要模擬這種登陸的方式,很多大的公司已經實現了這

Spring boot——logback.xml 配置(二)

原文地址:https://www.cnblogs.com/lixuwu/p/5810912.html                   https://aub.iteye.com/blog/1101260 閱

5 Spring 入門 web.xml配置

1.在WEB-INF的lib下面匯入jar包2.在web.xml裡面配置Spring Mvc ,即,配置DispatcherServlet。(DispatcherServlet實際上就是一個servlet。)3. 啟動Spring4.spring-servlet.xml配置【

Spring MVC框架搭建及其

handler 類型 blog velocity api 前綴 oci 使用 tiles  現在主流的Web MVC框架除了Struts這個主力 外,其次就是Spring MVC了,因此這也是作為一名程序員需要掌握的主流框架,框架選擇多了,應對多變的需求和業務時,可實行的方

spring security 基礎入門(配置)

<filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterPr

Spring Cloud中Feign配置

到目前為止,小夥伴們對Feign的使用已經掌握的差不多了,我們在前文也提到Feign是對Ribbon和Hystrix的整合,那麼在Feign中,我們要如何配置Ribbon和Hystrix呢?帶著這兩個問題,我們來看看本文的內容。 本文是Spring

Spring整合Mybatis關鍵配置

根據官方的說法,在ibatis3,也就是Mybatis3問世之前,Spring3的開發工作就已經完成了,所以Spring3中還是沒有對Mybatis3的支援。因此由Mybatis社群自己開發了一個Mybatis-Spring用來滿足Mybatis使用者整合Spring的需求

Spring Cloud Eureka 常用配置,建議收藏!

new enable seconds 指定 頻率 集群 系列 name tps 前幾天,棧長分享了 《Spring Cloud Eureka 註冊中心集群搭建,Greenwich 最新版!》,今天來分享下 Spring Cloud Eureka 常用的一些參數配置及說明。

純幹貨,Spring-data-jpa(轉)

數據庫表結構 attribute 類型 n+1 asq sep pointcut 如何 odin 本篇進行Spring-data-jpa的介紹,幾乎涵蓋該框架的所有方面,在日常的開發當中,基本上能滿足所有需求。這裏不講解JPA和Spring-data-jpa單獨使用,所有的

spring-dataspring-data-jpa:簡單三步快速上手spring-data-jpa開發

事務管理 out don 前言 map lns xid public lease 前言: 基於spring framework 4.x或spring boot 1.x開發環境 務必註意以下版本問題:Spring framework4.x(Spring boot1.x)對應s