Spring Data JPA入門案例
阿新 • • 發佈:2018-12-22
目錄
1. Spring Data JPA介紹
Spring Data JPA 是 Spring 基於 ORM 框架、JPA 規範的基礎上封裝的一套JPA應用框架,可使開發者用極簡的程式碼即可實現對資料庫的訪問和操作。它提供了包括增刪改查等在內的常用功能。
Spring Data JPA 讓我們解脫了DAO層的操作,基本上所有CRUD都可以依賴於它來實現,在實際的工作工程中,推薦使用Spring Data JPA + ORM(如:hibernate)完成操作。簡單來說,平常我們開發時需要寫dao層介面和介面的實現類,而使用Spring Data JPA時只需要編寫一個符合springDataJpa的dao層介面,不需要編寫實現類。這個dao層介面規範:1.需要繼承兩個介面(JpaRepository,JpaSpecificationExecutor)2.需要提供響應的泛型。
2. Spring Data JPA與JPA規範,與hibernate的關係
JPA是一套規範,內部是有介面和抽象類組成的。hibernate是一套成熟的ORM框架,而且Hibernate實現了JPA規範,所以也可以稱hibernate為JPA的一種實現方式,我們使用JPA的API程式設計,意味著站在更高的角度上看待問題(面向介面程式設計)Spring Data JPA是Spring提供的一套對JPA操作更加高階的封裝,是在JPA規範下的專門用來進行資料持久化的解決方案。
3. 入門案例
3.1 建立工程匯入依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.itcast</groupId> <artifactId>jpa-day2</artifactId> <version>1.0-SNAPSHOT</version> <properties> <spring.version>5.0.2.RELEASE</spring.version> <hibernate.version>5.0.7.Final</hibernate.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <c3p0.version>0.9.1.2</c3p0.version> <mysql.version>5.1.6</mysql.version> </properties> <dependencies> <!-- junit單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- spring beg --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <!-- spring對orm框架的支援包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!-- spring end --> <!-- hibernate beg --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.1.Final</version> </dependency> <!-- hibernate end --> <!-- c3p0 beg --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0.version}</version> </dependency> <!-- c3p0 end --> <!-- log end --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- spring data jpa 的座標--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.9.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- el beg 使用spring data jpa 必須引入 --> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.4</version> </dependency> <!-- el end --> <!--JDK9版本對於JPA必須匯入的依賴--> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> </dependencies> </project>
3.2 配置spring和Spring Data JPA的配置檔案
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <!--spring 和 spring data jpa的配置--> <!-- 1.建立entityManagerFactory物件交給spring容器管理--> <bean id="entityManagerFactoty" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <!--配置的掃描的包(實體類所在的包) --> <property name="packagesToScan" value="com.heima.domain" /> <!-- jpa的實現廠家 --> <property name="persistenceProvider"> <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/> </property> <!--jpa的供應商介面卡 --> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <!--配置是否自動建立資料庫表 --> <property name="generateDdl" value="false" /> <!--指定資料庫型別 --> <property name="database" value="MYSQL" /> <!--資料庫方言:支援的特有語法 --> <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" /> <!--是否顯示sql --> <property name="showSql" value="true" /> </bean> </property> <!--jpa的方言 :高階的特性 --> <property name="jpaDialect" > <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" /> </property> </bean> <!--2.建立資料庫連線池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="jdbcUrl" value="jdbc:mysql:///jpa_day1" ></property> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> </bean> <!--3.整合spring dataJpa--> <jpa:repositories base-package="com.heima.dao" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactoty" ></jpa:repositories> <!--4.配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactoty"></property> </bean> <!--第一種配置方式--> <tx:annotation-driven proxy-target-class="true"></tx:annotation-driven> <!--第二種配置方式--> <!-- 4.txAdvice--> <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice>--> <!-- 5. 配置包掃描--> <context:component-scan base-package="com.heima" ></context:component-scan> </beans>
3.3 編寫實體類和資料庫表的對映關係
package com.heima.domain;
import javax.persistence.*;
@Entity
@Table(name = "cst_customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "cust_id")
private long custId;
@Column(name = "cust_name")
private String custName;
@Column(name = "cust_source")
private String custSource;
@Column(name = "cust_industry")
private String custIndustry;
@Column(name = "cust_level")
private String custLevel;
@Column(name = "cust_address")
private String custAddress;
@Column(name = "cust_phone")
private String custPhone;
....省略setter和getter方法,toString方法
}
3.4 編寫dao層介面
package com.heima.dao;
import com.heima.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* 符合SpringDataJpa的dao層介面規範
* JpaRepository<操作的實體類型別,實體類中主鍵屬性的型別>
* * 封裝了基本CRUD操作
* JpaSpecificationExecutor<操作的實體類型別>
* * 封裝了複雜查詢(分頁)
*/
public interface CustomerDao extends JpaRepository<Customer,Long>,JpaSpecificationExecutor<Customer> {
}
3.5 編寫測試類
package com.heima.test;
import com.heima.dao.CustomerDao;
import com.heima.domain.Customer;
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 java.util.List;
@RunWith(SpringJUnit4ClassRunner.class) //宣告spring提供的單元測試環境
@ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置資訊
public class CustomerDaoTest {
@Autowired
private CustomerDao customerDao;
/**
* 根據id查詢
*/
@Test
public void testFindOne() {
Customer customer = customerDao.findOne( 3l );
System.out.println( customer );
}
/**
* save : 儲存或者更新
* 根據傳遞的物件是否存在主鍵id,
* 如果沒有id主鍵屬性:儲存
* 存在id主鍵屬性,根據id查詢資料,更新資料
*/
@Test
public void testSave(){
Customer customer = new Customer();
customer.setCustName( "黑馬程式設計師" );
customer.setCustSource( "鄭州it教育" );
customerDao.save( customer );
}
/**
* 查詢所有
*/
@Test
public void testFindAll(){
List<Customer> customers = customerDao.findAll();
for(Customer customer : customers){
System.out.println(customer);
}
}
/**
* 測試統計查詢:查詢客戶的總數量
* count:統計總條數
*/
@Test
public void testCount() {
long count = customerDao.count();//查詢全部的客戶數量
System.out.println(count);
}
/**
* 測試:判斷id為4的客戶是否存在
* 1. 可以查詢以下id為4的客戶
* 如果值為空,代表不存在,如果不為空,代表存在
* 2. 判斷資料庫中id為4的客戶的數量
* 如果數量為0,代表不存在,如果大於0,代表存在
*/
@Test
public void testExists() {
boolean exists = customerDao.exists(1l);
System.out.println("id為4的客戶 是否存在:"+exists);
}
/**
* 根據id從資料庫查詢
* @Transactional : 保證getOne正常執行
*
* findOne:
* em.find() :立即載入
* getOne:
* em.getReference :延遲載入
* * 返回的是一個客戶的動態代理物件
* * 什麼時候用,什麼時候查詢
*/
@Test
// @Transactional
public void testGetOne() {
Customer customer = customerDao.getOne(4l);
System.out.println(customer);
}
}