SpringDataJPA是Spring基於ORM框架,JPA規範的基礎上封裝的一套JPA應用框架。
1.首先創建一個maven環境,並導入座標
pom.xml文件的導入
<properties>
<spring.version>5.2.7.RELEASE</spring.version>
<hibernate.version>5.4.10.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>
<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>
<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>5.2.7.RELEASE</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 -->
</dependencies>
然後是在resource文件夾下創建一個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: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.w.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="123456"></property>
<property name="jdbcUrl" value="jdbc:mysql:///springdata" ></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
</bean>
<!--3.整合spring dataJpa-->
<jpa:repositories base-package="com.w.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>
<!-- 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.aop-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.w.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
</aop:config>
<!--5.聲明式事務 -->
<!-- 6. 配置包掃描-->
<context:component-scan base-package="com.w" ></context:component-scan>
</beans>
然後在對應的com.w.domain下面創建實體類
package com.w.domain;
import javax.persistence.*;
@Entity
@Table(name="cst_customer")
public class Customer {
//主鍵
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="cust_id")
private Long cId;
//客戶名稱
@Column(name="cust_name")
private String cName;
//客戶來源
@Column(name="cust_source")
private String cSource;
//所屬行業
@Column(name="cust_industry")
private String cIndustry;
//等級
@Column(name="cust_level")
private String cLevel;
//地址
@Column(name="cust_address")
private String cAddr;
//電話
@Column(name="cust_phone")
private String cPhone;
public Long getcId() {
return cId;
}
public void setcId(Long cId) {
this.cId = cId;
}
public String getcName() {
return cName;
}
public void setcName(String cName) {
this.cName = cName;
}
public String getcSource() {
return cSource;
}
public void setcSource(String cSource) {
this.cSource = cSource;
}
public String getcIndustry() {
return cIndustry;
}
public void setcIndustry(String cIndustry) {
this.cIndustry = cIndustry;
}
public String getcLevel() {
return cLevel;
}
public void setcLevel(String cLevel) {
this.cLevel = cLevel;
}
public String getcAddr() {
return cAddr;
}
public void setcAddr(String cAddr) {
this.cAddr = cAddr;
}
public String getcPhone() {
return cPhone;
}
public void setcPhone(String cPhone) {
this.cPhone = cPhone;
}
@Override
public String toString() {
return "Customer{" +
"cId=" + cId +
", cName='" + cName + '\'' +
", cSource='" + cSource + '\'' +
", cIndustry='" + cIndustry + '\'' +
", cLevel='" + cLevel + '\'' +
", cAddr='" + cAddr + '\'' +
", cPhone='" + cPhone + '\'' +
'}';
}
}
以及實體類對應的sql,在我的上一章節搭建JPA項目中有
接着就是創建對應的Dao接口,需要繼承
JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer>兩個接口
package com.w.dao;
import com.w.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface CustomDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
@Query(value = "from Customer where cId = ?2 and cName = ?1",nativeQuery = false)
Customer getCustomerByNameAndId(String name,long id);
@Query("update Customer set cName=?2 where cId=?1")
@Modifying
void updateCustomerById(long id,String name);
Customer findByCNameLikeAndCAddr(String cName, String cAddr);
Customer findByCName(String cName);
}
接着編寫測試類
package com.w.test;
import com.w.dao.CustomDao;
import com.w.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)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestCRUD {
@Autowired
private CustomDao customDao;
@Test
public void testFindAll() {
List<Customer> customers = customDao.findAll();
System.out.println(customers);
}
@Test
public void testFindOne() {
Customer customer = customDao.findOne(1L);
System.out.println(customer);
}
@Test
public void testSave() {
Customer customer =new Customer();
customer.setcName("張三小瘋子");
customer.setcAddr("上海");
customDao.save(customer);
}
@Test
public void testDelete() {
customDao.delete(4L);
}
@Test
public void testCount(){
System.out.println(customDao.count());
}
@Test
public void testExist(){
//查看是否存在該對象
System.out.println(customDao.exists(4L));
}
}
這裏面都是一些springData裏面有的方法
如果使用JPQL語句進行查詢
則還需要添加對應的方法在dao接口中,我已經在裏面定義完了,可以照着操作
package com.w.test;
import com.w.dao.CustomDao;
import com.w.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestJPQL {
@Autowired
private CustomDao customDao;
@Test
public void testFindByNameAndId(){
System.out.println(customDao.getCustomerByNameAndId("張三",1L));
}
@Test
@Transactional
@Rollback(value = false)
public void testUpdate(){
customDao.updateCustomerById(2,"小趙");
}
}
最後是根據命名規範進行查找
package com.w.test;
import com.w.dao.CustomDao;
import com.w.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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestOthers {
@Autowired
private CustomDao customDao;
@Test
public void test1(){
Customer customer = customDao.findByCNameLikeAndCAddr("%張%","上海");
//Customer customer = customDao.findByCName("%張%");
System.out.println(customer);
}
}